如何从AVAudioPlayer中的核心数据播放NSData [英] How to play NSData from Core Data in AVAudioPlayer
问题描述
我将mp3文件作为NSData二进制数据保存到Core Data中.然后,我在NSFetchedResultsController
的帮助下加载此文件.然后,我编写了以下代码,但出现了错误.我该如何解决?
I save mp3 file into Core Data as NSData binary data. Then I load this file with help of NSFetchedResultsController
. Then I wrote following code but I got the error. How can I fix it?
致命错误:解开可选值时意外发现nil
fatal error: unexpectedly found nil while unwrapping an Optional value
var audioPlayer = AVAudioPlayer()
func play() {
if musicData != nil {
audioPlayer = AVAudioPlayer(data: musicData, error: nil)
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
audioPlayer.prepareToPlay()
audioPlayer.play()
}
}
更新
我检查了一下,发现AVAudioPlayer
为nil,但我在本课开始时就将此玩家初始化.
UPDATE
I checked it and I saw that AVAudioPlayer
is nil but I init this player in beginning of this class.
仍然更改了代码,但出现了相同的错误 第二种方法
Still I changed code but I get the same error The second method
var av = AVAudioPlayer()
func play() {
let object = fetchedResultsController.fetchedObjects?.first as! Entity
let songData = object.mp3
var urlData: NSURL!
songData.writeToURL(urlData, atomically: true)
av = AVAudioPlayer(contentsOfURL: urlData, error: nil)
av.prepareToPlay()
av.play()
}
推荐答案
我添加了文件类型提示,并且对我有用.
I added the file type hint and it works for me.
func playMusic() {
let url = NSBundle.mainBundle().URLForResource("Music", withExtension: "mp3")!
let data = NSData(contentsOfURL: url)!
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
audioPlayer = AVAudioPlayer(data: data, fileTypeHint: AVFileTypeMPEGLayer3, error: nil)
audioPlayer.prepareToPlay()
audioPlayer.play()
}
这篇关于如何从AVAudioPlayer中的核心数据播放NSData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!