同时异步播放多个AVAudioPlayer?

时间:2019-03-17 16:43:16

标签: swift avfoundation avaudioplayer avkit dispatch-queue

我有一个背景AVAudioPlayer,通常可以正常工作。现在,我有一些事件会延迟触发异步动作,在这里我想播放另一种声音,而另一种声音应该继续播放。所以我做了一个新的:

DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
    guard let urlStr = Bundle.main.path(forResource: "File1", ofType: ".mp3") else { fatalError() }
    self.player = try? AVAudioPlayer(contentsOf: URL(fileURLWithPath: urlStr), fileTypeHint: "mp3")
    self.player?.play()
}

DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
    guard let urlStr = Bundle.main.path(forResource: "File2", ofType: ".mp3") else { fatalError() }
    let p = try? AVAudioPlayer(contentsOf: URL(fileURLWithPath: urlStr), fileTypeHint: "mp3")
    p?.play()
}

因此第一个运行正常(仅调度以表明它也在异步运行)。第二个也运行,这意味着没有错误。但是,我只听到第一个...

1 个答案:

答案 0 :(得分:1)

Why do you create a new player inside you async call? I had similar problems and it should work if you declare a new var outside your immediate async-scope.