我总是遇到致命的错误:在展开Optional值时意外地发现了nil。但如果我查看fileURL变量,它有一些值。请让我知道我错过了什么:
错误:
Optional(http:/files.parsetfss.com/461a4eda-d153-4d46-bd85-28ddd355a94c/tfss-03d4eb57-51cb-424d-8c90-2d8a89429203-00255--How_To_Build_A_Loving_Family.mp3 -- file:///)
fatal error: unexpectedly found nil while unwrapping an Optional value
代码:
if let audioFile = object["audioFile"] as? PFFile {
var audioPath: String = audioFile.url!
var fileURL = NSURL(fileURLWithPath: audioPath as String)
println(fileURL)
audioPlayer = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
audioPlayer.volume = volumeSlider.value
audioPlayer.play()
}
答案 0 :(得分:0)
此代码适用于您的网址:
let url = "http://files.parsetfss.com/461a4eda-d153-4d46-bd85-28ddd355a94c/tfss-03d4eb57-51cb-424d-8c90-2d8a89429203-00255--How_To_Build_A_Loving_Family.mp3"
let soundData = NSData(contentsOfURL: NSURL(string: url)!)
var error: NSError?
self.audioPlayer = AVAudioPlayer(data: soundData, error: &error)
if audioPlayer == nil
{
if let e = error
{
println(e.localizedDescription)
}
}
audioPlayer!.volume = 1.0
audioPlayer!.prepareToPlay()
audioPlayer!.play()
通过这种方式,您可以将音频转换为需要一些时间播放音频的数据。
这是播放歌曲的另一种方式:
let url = audioFile.url!
let playerItem = AVPlayerItem( URL:NSURL( string:url ) )
player = AVPlayer(playerItem:playerItem)
player.rate = 1.0;
player.play()