Search code examples
swiftavfoundationavaudioplayeravkitdispatch-queue

play multiple AVAudioPlayer at the same time asynchronously?


I have a background AVAudioPlayer who normally works just fine. Now I have some event that triggers an asynchron action with a delay, here I want to play another sound while the other should keep playing. So I make a new one:

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

So the first one runs normally (Dispatch only to show that it's working also async). The second one runs as well, meaning no error. However, I only hear the first one...


Solution

  • 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.