ios - AVAudioPlayer 第一次不播放

标签 ios swift avaudioplayer

第一次按下按钮时,我无法通过 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/

相关文章:

swift - 在 swift 中创建 Singleton 类?

ios - 设置当前时间为yyyy-MM-dd 00 :00:00 using Swift

ios - swift turn-by-turn 映射 ios

ios - 在AVAudioPlayer中停止声音并显示AQDefaultDevice(173):跳过输入流错误日志

objective-c - 应用程序处于后台时中断后恢复执行代码

ios - 加载主视图或单元格时在 UITableViewCell Swift 中运行代码

ios - 错误域=com.alamofire.error.serialization.response 代码=-1011“请求失败 : bad request (400)

iphone - UITableView 在 cellForRow 中使用 selectRowAtIndexPath 导致双高亮

swift - AVAudioFile 中的 URL 为 nil

objective-c - 淡出 UIView?