AVAudioPlayer - playing multiple audio files, in sequence

后端 未结 5 810
忘了有多久
忘了有多久 2020-12-16 06:14

I want to play multiple MP3 files, in sequence (one after the other) , using AVAudioPlayer. I tried it, and it stops after playing the first MP3. However, if I go into deb

5条回答
  •  清歌不尽
    2020-12-16 06:31

    It is a good idea to initialize, prepare the items, and queue ahead of time, for example on the viewDidLoad method.

    If you are working on Swift,

        override func viewDidLoad() {
            super.viewDidLoad()
            let item0 = AVPlayerItem.init(URL: NSBundle.mainBundle().URLForResource("url", withExtension: "wav")!)
    
            let item1 = AVPlayerItem.init(URL: NSBundle.mainBundle().URLForResource("dog", withExtension: "aifc")!)
            let item2 = AVPlayerItem.init(URL: NSBundle.mainBundle().URLForResource("GreatJob", withExtension: "wav")!)
    
    
            let itemsToPlay:[AVPlayerItem] = [item0, item1, item2] 
            queuePlayer = AVQueuePlayer.init(items: itemsToPlay)
        }
    

    and then when an event occurs,

     queuePlayer.play()
    

    Notice that if you use the queue, you still might have some gaps between the sounds.

    You can find the Objective-C version in the question How to do something when AVQueuePlayer finishes the last playeritem

    Hope it helps.

提交回复
热议问题