如何在 SwiftUI 项目中使用 AVAudioPlayer 播放音频

dee*_*shi 8 avfoundation avaudioplayer ios swift5 swiftui

使用这种方法不播放音频。play() 函数正在执行,没有任何错误。 请帮忙

var audioPlayer = AVAudioPlayer()
let path = Bundle.main.path(forResource: "a", ofType: "mp3")
@State var isPlaying : Bool = false

var body: some View {
    Button(action: {
         self.isPlaying.toggle()    
         let url = URL(fileURLWithPath: self.path!)
         do {
             self.audioPlayer = try AVAudioPlayer(contentsOf: url)
             self.audioPlayer.prepareToPlay()
             self.audioPlayer.play()
         }catch {
             print("Eror")
         }        
      }, label: {
           if isPlaying {
                    Image(systemName: "pause")
                    .font(Font.system(.largeTitle).bold())
           }else {
                Image(systemName: "play.fill")
                 .font(Font.system(.largeTitle).bold())
           }
    })
}
Run Code Online (Sandbox Code Playgroud)

Ann*_*ova 17

音频文件在吗?请选择项目,转到“构建阶段”选项卡,在“复制捆绑资源”下,您必须看到音频文件。如果它在那里,那么问题是这样的。

我试过你的代码,它播放了声音然后崩溃了。我像这样改变它以使其工作

 @State var audioPlayer:AVAudioPlayer?

 @State var isPlaying : Bool = false

 var body: some View {

     Button(action: {

         if let path = Bundle.main.path(forResource: "a", ofType: ".mp3") {

             self.audioPlayer = AVAudioPlayer()

             self.isPlaying.toggle()

             let url = URL(fileURLWithPath: path)

             do {
                 self.audioPlayer = try AVAudioPlayer(contentsOf: url)
                 self.audioPlayer?.prepareToPlay()
                 self.audioPlayer?.play()
             }catch {
                 print("Error")
             }
         }

     }, label: {
Run Code Online (Sandbox Code Playgroud)

----

您是否考虑过将音频模型与 UI 分开?如果你把它放在单独的 Swift 文件中,它会让你的代码更清晰

import AVFoundation

 class Sounds {

   static var audioPlayer:AVAudioPlayer?

   static func playSounds(soundfile: String) {

       if let path = Bundle.main.path(forResource: soundfile, ofType: nil){

           do{

               audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
               audioPlayer?.prepareToPlay()
               audioPlayer?.play()

           }catch {
               print("Error")
           }
       }
    }
 }
Run Code Online (Sandbox Code Playgroud)

只需一行即可在 UI 中使用它

var body: some View {
    Button(action: {
        self.isPlaying.toggle()
        Sounds.playSounds(soundfile: "0.wav")

    }, label: {
Run Code Online (Sandbox Code Playgroud)