-2

I am trying to play some sound files with buttons but pressing the button throws me this error Thread 1: EXC_BAD_ACCESS (code=1, address=0x58) on line

audioPlayer.play()

I have looked for possible solutions and I can't find anything related to that error, the function of my code runs well until the print, this is my complete code.

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var track: String? = nil
    var audioPlayer = AVAudioPlayer()

    @IBAction func heavyButton(_ sender: Any) {
        track = "H"
        print("heavy machine gun \(track!)")
        reproducirAudio(audio: track!)
        audioPlayer.play()
    }

    func reproducirAudio(audio: String) {
        do {
            print("entro a la funcion de reproducir")
            audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: audio, ofType: "mp3")!))
            audioPlayer.prepareToPlay()
        } catch {
            print(error)
        }
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Abel Lazaro
  • 11
  • 1
  • 6
  • Are you sure `reproducirAudio` was able to construct `AVAudioPlayer` instance? – Jean-Baptiste Yunès Oct 20 '19 at 13:25
  • You are saying `Bundle.main.path(forResource: audio, ofType: "mp3")!`. That means: "If you can't find the file, please crash my program." That is what you asked for, and that is what is happening. Note that you will _not_ catch an error when this happens; this is an exception, not an error. – matt Oct 20 '19 at 13:34
  • Two potential errors: If `URL.init(fileURLWithPath: Bundle.main.path(forResource: audio, ofType: "mp3")` is nil, you'll crash. But there is also a new behavior in iOS 13: Don't do `var audioPlayer = AVAudioPlayer()`. There is no more "init with no params", in doc. – Larme Oct 21 '19 at 07:54
  • Cf. https://stackoverflow.com/questions/58166133/re-assigning-instance-of-avaudioplayer-in-ios13-leads-to-bad-access-runtime-erro/58200447#58200447 https://stackoverflow.com/questions/58110827/ios-13-1-crash-in-avaudio-player etc. – Larme Oct 21 '19 at 07:55

1 Answers1

0

i found a solution, this is for iOS13

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var track: String? = nil
    var audioPlayer: AVAudioPlayer?

@IBAction func heavyButton(_ sender: Any) {
    track = "H"
    print("heavy machine gun \(track!)")
    reproducirAudio(audio: track!)
}

func reproducirAudio(audio: String) {
    let path = Bundle.main.path(forResource: "\(audio).mp3", ofType:nil)!
    let url = URL(fileURLWithPath: path)

    do {
       audioPlayer = try AVAudioPlayer(contentsOf: url)
       audioPlayer?.play()
    } catch {
        // couldn't load file :(
      }
}
Abel Lazaro
  • 11
  • 1
  • 6