Swift: AVAudioPlayer using array suddenly mutes

五迷三道 提交于 2019-12-12 03:37:43

问题


I've written a small class that uses AVFoundation to play audio using an array. Basically an new element is appended to the array every time 'playAudio' is called. This allows multiple sounds to play without cutting each other off. Also, so that the array doesn't infinitely increase in size I've set it to cycle back to index 0 after filling 5 slots in the array. Now everything works perfectly but after 'audioPlayer' has been called a bunch of times, audio suddenly stops and I start getting the 'Error' in the Catch section but my app continues to function normally as if it has just been muted. Can anyone tell me why this is happening?

var audioIndexA = 0

public class AudioPlayer: NSObject {

var playerA = [AVAudioPlayer]()

func playAudio(audioFile audioFile: String){

    do{

        let path = NSBundle.mainBundle().pathForResource(audioFile, ofType:"wav")
        let fileURL = NSURL(fileURLWithPath: path!)
        playerA.insert(try AVAudioPlayer(contentsOfURL: fileURL, fileTypeHint: nil), atIndex: audioIndexA)
        playerA[audioIndexA].prepareToPlay()

        if audioIndexA < 5{

            playerA[audioIndexA].play()
            audioIndexA++

        } else{

            playerA[audioIndexA].play()
            audioIndexA = 0
        }

    } catch{

        print("Error")
    }
}

}

来源:https://stackoverflow.com/questions/31785088/swift-avaudioplayer-using-array-suddenly-mutes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!