按顺序快速播放音频文件 [英] Play audio file in a sequence usign swift

查看:158
本文介绍了按顺序快速播放音频文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个职能.第一个循环播放要播放的音频的名称列表,第二个循环是实际的播放器功能.问题是它只播放最后一个.它不会一一播放直到下一个播放完成.如何顺序执行?我尝试添加:dispatch_after(DISPATCH_TIME_NOW,dispatch_get_main_queue(),{})...仍然不起作用.任何可能的解决方案.先感谢您!

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 {

            }

    }

推荐答案

使用 AVQueuePlayer (在开始时将其与Items一起初始化,然后将其依次播放在队列中))类,而不是 AVAudioPlayer .

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()

这篇关于按顺序快速播放音频文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆