我试图播放来自Parse.com的音频文件。运行此代码后,我在获取数据时出现 错误! 打印出来。我无法理解为什么会发生这种情况。我认为网址是正确的。当我在浏览器中尝试它时,它开始下载我试图播放的音乐。谁能告诉我这段代码有什么问题或者如何解决这个问题?
let query = PFQuery(className: "AudioFile")
query.whereKeyExists("audio")
query.findObjectsInBackgroundWithBlock { (objects:[PFObject]?, error: NSError?) -> Void in
if error == nil {
let audio = objects?[0]
let audioFile = audio?["audio"] as? PFFile
let filePath = audioFile?.url
let url = NSURL(fileURLWithPath: filePath!)
let soundData = NSData(contentsOfURL: url)
if soundData != nil {
do {
self.audioPlayer = try AVAudioPlayer(data: soundData!) // AVAudioPlayer(contentsOfURL: url)
self.audioPlayer.prepareToPlay()
self.audioPlayer.volume = 1.0
self.audioPlayer.play()
} catch {
print("Error occured while playing music!")
}
} else {
print("Error occured while getting data!")
}
} else {
print("Error occured while downloading file!")
}
}
答案 0 :(得分:0)
我用这种方式改变了代码。
query.whereKeyExists("audio")
query.findObjectsInBackgroundWithBlock { (objects:[PFObject]?, error: NSError?) -> Void in
if error == nil {
let audio = objects?[0]
let audioFile = audio?["audio"] as? PFFile
audioFile?.getDataInBackgroundWithBlock({ (audio: NSData?, error: NSError?) -> Void in
if audio != nil {
do {
self.audioPlayer = try AVAudioPlayer(data: audio!)
self.audioPlayer.prepareToPlay()
self.audioPlayer.delegate = self
self.audioPlayer.volume = 10.0
self.audioPlayer.play()
} catch {
print("Error occured while playing music!")
}
} else {
print ("Somehow audio is nil!")
}
})
} else {
print("Error occured while downloading file!")
}
}
值1.0表示音频播放器的全音量,但我无法在模拟器上听到它,所以我使用了10.0。在第一种情况下NSData是零,所以我不得不改变那部分代码并使用getDataInBackgroundWithBlock。此方法是parse方法,它以异步方式查找对象并使用结果调用给定的块。在块中,NSData不再存在,因此AVAudioPlayer正常工作。