我正在尝试从远程 URL 播放音频。
let audioData = try! Data.init(contentsOf: URL)
do
{
self.audioPlayer = try AVAudioPlayer.init(data: data) //Throwing error sometimes
self.audioPlayer?.delegate = self
self.audioPlayer?.prepareToPlay()
self.audioPlayer?.play()
}
catch {
showErrorMessage("An error occurred while trying to extract audio file")
}
我的服务器上有一个音频 url 列表。 对于某些音频 我能够获取Data
但在AVAudioPlayer 的init 方法中它抛出错误。我无法找到真正的原因。
我有 AVPlayer
的选项,但为什么这个东西会导致问题?
最佳答案
直接从您拥有的 URL 播放音频
do
{
try Manager.player = AVAudioPlayer.init(contentsOf: returnPathAtSelectedIndex(fileName: fileName))
//Set required delegates and Values
Manager.player?.delegate = self
Manager.player?.volume = 1.0
Manager.player?.prepareToPlay()
Manager.player?.play()
}
catch
{
print("Error while playing music: \(error.localizedDescription)")
}
我的播放器
struct Manager
{
///AVAudio Player
static var player: AVAudioPlayer?
}
我的函数 func returnPathAtSelectedIndex(fileName:String) -> URL
返回一个 URL
。
编辑
作为AVAudioPlayer播放保存到本地的文件。您需要将文件保存到本地而不是
AVAudioPlayer.init(contentsOf:localFileUrl)
将有助于播放文件并且不会产生崩溃。
关于ios - AVAudioPlayer.initWithData 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49993885/