How to play a song from user's local music library?

Viewed 388

I'm trying to play a song that is stored locally on my device in the Music app. I try to load the assetURL in AVAudioPlayer, but every time I interact with the MPMedia Query...I get the following error

[iTunesCloud] [ICUserIdentityStore] Failed to fetch local store account with error: Error Domain=com.apple.accounts Code=9 "(null)"

The code is simple

MPMediaLibrary.requestAuthorization { (status) in
   if status == .authorized {              
       let query = MPMediaQuery.songs()
       if let songs = query.items {
               let bestSong = songs[50]
               self.audioPlayer = try! AVAudioPlayer(contentsOf: bestSong.assetURL!)
        }
    }
}

Is there some config setting I'm missing? What's curious is that I can get the list of songs. I can even get the title and assetURLs. But this error appears and the song will not play.

This seems to be a similar issue https://forums.developer.apple.com/thread/132245

1 Answers

So turns out I just needed to put the following line before the code above

try! AVAudioSession.sharedInstance().setCategory(.playback)
Related