0

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?

user
  • 1
  • 1
  • This issue has been solved here: https://stackoverflow.com/questions/58110827/ios-13-1-crash-in-avaudio-player – Ahmad.Net Sep 28 '19 at 14:03

2 Answers2

1

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{
}
  • This removes the crash for me, but the sound doesn't work and the player seems to not get instantiated. Does the sound work for you or does this only resolve the crash? – nullforlife Oct 02 '19 at 09:20
  • 1
    @nullforlife before instantiating your AV(Audio)Player, add the following line: `try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)` – 10623169 Oct 16 '19 at 14:22
  • This stopped the crash for me. But sound did not play. I think it is a simulator bug. That AVAudioPlayer bug occurs when I use simulator ipads with low version. – Alexander Langer Feb 22 '22 at 09:33
1

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.

Tushar Moradiya
  • 780
  • 1
  • 6
  • 13