尝试使用以下代码播放AMR音频文件:
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)
}
}
我绝对相信:
该怎么做以及如何修复它?
答案 0 :(得分:1)
问题在于
guard let player = player else { return }
您正在使用非可选的本地副本替换外部可选AVAudioPlayer
。您在本地副本上调用play()
,然后在闭包完成时,它超出范围并被删除。
试试这个。
player = try AVAudioPlayer(data: data, fileTypeHint: AVFileType.amr.rawValue)
player?.volume = 1.0
player?.prepareToPlay()
player?.play()
} catch {