How to play NSData from Core Data in AVAudioPlayer

∥☆過路亽.° 提交于 2019-12-11 13:32:29

问题


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?

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()
    }
}

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()
}

回答1:


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()
    }


来源:https://stackoverflow.com/questions/32510346/how-to-play-nsdata-from-core-data-in-avaudioplayer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!