Search code examples
iosswiftnsdataavaudioplayer

How to play NSData from Core Data in AVAudioPlayer


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

Solution

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