斯威夫特3:AVAudioPlayer没有播放声音

问题描述:

我在它与我的音频播放器的结构体:斯威夫特3:AVAudioPlayer没有播放声音

struct MT_Audio { 

    func playAudio(_ fileName:String, _ fileExtension:String, _ atVolume:Float) { 
     var audioPlayer = AVAudioPlayer() 
     if let audioPath = Bundle.main.path(forResource: fileName, ofType: fileExtension) { 
      let audioURL = URL(string:audioPath) 
      do { 
       audioPlayer = try AVAudioPlayer(contentsOf: audioURL!) 
       audioPlayer.volume = atVolume 
       audioPlayer.prepareToPlay() 
       audioPlayer.play() 
      } catch { 
       print(error) 
      } 
     } 
    } 
} 

//I'm calling it in viewDidLoad like this: 

    guard let fileURL = Bundle.main.url(forResource:"heartbeat-01a", withExtension: "mp3") 
     else { 
       print("can't find file") 
       return 
      } 

     let myAudioPlayer = MT_Audio() //<--RESOLVED THE ISSUE BY MAKING THIS A PROPERTY OF THE VIEWCONTROLLER 
     myAudioPlayer.playAudio("heartbeat-01a", "mp3", 1.0) 

因为它不和好如初的,我知道该文件的后卫是存在的。在尝试之后,我也提出了一个突破点,并且我正在接触音频播放器。当我去实际的文件,并在Xcode中点击它播放。这在模拟和设备上都会失败。任何帮助,将不胜感激。

+0

,看一下在Xcode右侧面板中。选择文件时,应检查目标成员资格。如果没有,请检查并重试。 –

+0

我在发帖前检查过。但谢谢你的建议。 – PruitIgoe

+0

_注意_你应该避免在'audioURL!'中包含''隐含的解包可选''。 Bundle.main提供了一个url方法,它返回一个可选的url使用,而不是'if let audioUrl = Bundle.main.url(forResource:fileName,withExtension:fileExtension)' – Lamar

看起来像你的audioPlayer只存储在你的playAudio功能。

尽量保持audioPlayer因为这样你的类内的变量:

struct MT_Audio { 

    var audioPlayer: AVAudioPlayer? 

    mutating func playAudio(_ fileName:String, _ fileExtension:String, _ atVolume:Float) { 

     // is now member of your struct -> var audioPlayer = AVAudioPlayer() 
     if let audioPath = Bundle.main.path(forResource: fileName, ofType: fileExtension) { 
      let audioURL = URL(string:audioPath) 
      do { 
       let audioPlayer = try AVAudioPlayer(contentsOf: audioURL!) 
       audioPlayer.volume = atVolume 
       audioPlayer.prepareToPlay() 
       audioPlayer.play() 
      } catch { 
       print(error) 
      } 
     } 
    } 
} 
+0

感谢您的建议。仍然没有获得音频。不知道为什么将audioPlayer转换为结构中的全局变量对于播放音频是否重要。我在我的代码中检查过它,它被实例化了。文件路径是正确的。在Xcode中选择时播放mp3文件。这正成为grrrrr的一个早晨。 – PruitIgoe

+0

得到它的工作,你把我放在正确的轨道 - 看到我上面的评论和更改我的代码。 – PruitIgoe