EXC_BAD_ACCESS when using AVAudioPlayer



I am trying to use an AVAudioPlayer to play a song from iTunes, but I’m having a lot of difficulty.


Whenever I try to do something to my AVAudioPlayer even after giving it a URL, such as pausing it or trying to play at a certain time, my app crashes with EXC_BAD_ACCESS. I’ve looked online and it seems ike this is because I haven’t put a URL in, but I have already done that.


Let me run you through my code.


First, I make an AVAudioPlayer in the class-level.

var player = AVAudioPlayer()


Next, in a function called a short time after the viewDidLoad, I run this code.


//Gathering the song to play

        let songs = MPMediaQuery.songs()

       let predicateByGenre = MPMediaPropertyPredicate(value: "[EXACT SONG TITLE]", forProperty: MPMediaItemPropertyTitle)

        songs.filterPredicates = NSSet(object: predicateByGenre) as? Set
        let url = (songs.items![0]).assetURL
        do {
            try player = AVAudioPlayer(contentsOf: url!)
        } catch {
            fatalError("Could not load the file when trying to load a song in wander mode")
        //Updating the nowPlayingItem
        nowPlayingItem = songs.items![0]
       //nowPlayingItem is an MPMediaItem variable created so that the code can find out attributes about the current song when it needs to such as title, artist, etc.

        //Playing the player

Now, the player should hopefully have a url assigned to it with the song I have in my iTunes library I want it to play.


Now back to the viewDidLoad. In it, I have a small chunk of code:

delay(5, completion: {

The delay function is a function that, obivously, delays the code in completion argument by a set time defined in the argument just before.


Pausing the player seems like an easy thing to do, but when I do, the app crashes with EXC_BAD_ACCESS on the line where I try to pause it.

I don’t understand what I going on; the player should have a url and shouldn’t cause a bad access. Does anyone know what to do in this situation? Thanks in advance. Any help is appreciated.

Powered by WPeMatico

You may also like...

Comments are closed.