第一次按下按钮时,我无法通过 AVAudioPlayer 播放声音。当我再次点击它时,它工作正常。
这是我正在使用的代码,它在我的 viewDidLoad() 中被调用
func loadSounds(){
do{
try audioPlayerL = AVAudioPlayer(contentsOfURL: startListening!)
try audioPlayerE = AVAudioPlayer(contentsOfURL: doneListening!)
}
catch{
}
audioPlayerL.delegate = self
audioPlayerL.prepareToPlay()
audioPlayerE.delegate = self
audioPlayerE.prepareToPlay()
}
这是播放文件的方法
func playSound(){
if(startedListening == true){
audioPlayerL.play()
}
else{
audioPlayerE.play()
}
}
我完全不知道为什么它第一次没有播放。在模拟器上运行没有任何问题。在我的 iPhone 6 上运行加上第一次失败。
我检查了一下,它也没有在任何地方抛出错误。
最佳答案
只是这样就关闭了,任何有同样问题的人都知道这已经解决了。就像马尔可夫说的那样,添加这行代码就解决了问题
试试 AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers)
总数是这样的
一段加载声音的代码
func loadSounds(){
do{
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers)
try audioPlayerL = AVAudioPlayer(contentsOfURL: startListening!)
try audioPlayerE = AVAudioPlayer(contentsOfURL: doneListening!)
}
catch{
print("error")
}
audioPlayerL.delegate = self
audioPlayerL.prepareToPlay()
audioPlayerE.delegate = self
audioPlayerE.prepareToPlay()
}
被调用来播放声音的方法
func playSound(){
if(startedListening == true){
audioPlayerL.play()
}
else{
audioPlayerE.play()
}
}
关于ios - AVAudioPlayer 第一次不播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35359971/