Trying play AMR audio file using this code:
var player: AVAudioPlayer? = nil
WebService.shared.download(self.dataSource.object(at: indexPath)) { data in
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(data: data, fileTypeHint: AVFileType.amr.rawValue)
guard let player = player else { return }
print("Going to play: \(player.duration) seconds...")
player.volume = 1.0
player.prepareToPlay()
player.play()
} catch {
print(error.localizedDescription)
}
}
I'm absolutely sure that:
What's up and how fix it?
The problem is with
guard let player = player else { return }
You are replacing the outer, optional AVAudioPlayer
with a non-optional local copy. You call play()
on the local copy and then when the closure completes, it goes out of scope and is deleted.
Try this.
player = try AVAudioPlayer(data: data, fileTypeHint: AVFileType.amr.rawValue)
player?.volume = 1.0
player?.prepareToPlay()
player?.play()
} catch {