Play audio file in a sequence usign swift

谁说胖子不能爱 提交于 2019-12-12 01:40:46

问题


I have two functions. First one loops list of names for audio to be played, and the second one is the actual player function. The problem is that it plays only the last one. It does not play one by one waiting till the next is finished. How it possible to perform in a sequence? I tried to add: dispatch_after(DISPATCH_TIME_NOW, dispatch_get_main_queue(), { }) ... still does not work. Any possible solution. Thank you in advance!

func startGame(){
            audioPlay("NowListen")
            for i in 0...self.soundArray.count - 1 {
                    print(self.soundArray[i])
                    self.audioPlay(self.soundArray[i])
            }

        }



func audioPlay(name: String){
            var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("\(name)", ofType: "mp3")!)
            print(alertSound)
            // try to play sound
            do{
                self.audioPlayer = try AVAudioPlayer(contentsOfURL: alertSound)
                self.audioPlayer.prepareToPlay()
                self.audioPlayer.play()
            } catch {

            }

    }

回答1:


Use AVQueuePlayer ( init it with Items at the start and it will play in queue, one after another ) class instead of AVAudioPlayer.

In your Start Game, you can do following:

    var audioItems: [AVPlayerItem] = []
    for audioName in soundsArray {
        let url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(audioName, ofType: "mp3")!)
        let item = AVPlayerItem(URL: url)
        audioItems.append(item)
    }

    let player = AVQueuePlayer(items: audioItems)
    player.play()


来源:https://stackoverflow.com/questions/35844810/play-audio-file-in-a-sequence-usign-swift

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