user
user

Reputation: 1

AVAudioPlayer crashes on iOS 13

I use this code to play audio:

let url = Bundle.main.url(forResource: "0", withExtension: "mp3")!

            do {

                audioPlayer = try AVAudioPlayer(contentsOf: url)
                audioPlayer.delegate = self
                audioPlayer.prepareToPlay()
                play(sender:AnyObject.self as AnyObject)

            } catch {
            }

On iOS 12.4.1 on my iPhone X and iPhone 7 Plus this code work fine. But on iOS 13 and newer my app crashes on this line audioPlayer = try AVAudioPlayer(contentsOf: url) with error Thread 1: EXC_BAD_ACCESS (code=1, address=0x48). But on my simulator iPhone 11 Pro Max with iOS 13 all works fine. Why is this happening and how to fix?

Upvotes: 0

Views: 1409

Answers (2)

Tushar Moradiya
Tushar Moradiya

Reputation: 2118

You can instantiate your audioplayer like this :

var audioPlayer : AVAudioPlayer!

then please write this code :

do {
    self.audioPlayer = try AVAudioPlayer(contentsOf: sound)
    self.audioPlayer.play()
   }catch {}

This works for me.

Upvotes: 1

Lelio Junior
Lelio Junior

Reputation: 11

I had this error too, you are probably instantiating your audioPlayer like this:

let audioPlayer = AVAudioPlayer ()

try to create an Optional:

let audioPlayer: AVAudioPlayer?

and finish your code in viewDidLoad():

let path = Bundle.main.path (forResource: "0", ofType: "mp3")!
let url = URL(fileURLWithPath: path)
do {
   audioPlayer = try AVAudioPlayer(contentsOf: url)
} catch{
}

Upvotes: 1

Related Questions