Search code examples
iosswiftaudioavaudioplayer

Thread1:EXC_BAD_ACCESS(code=1, address = 0X48) AVAudioPlayer (Swift)


I get a Thread1:EXC_BAD_ACCESS(code=1, address = 0X48) every time I press a button. I checked my connections and my mp3 file "song" is correct. I'm not sure what's wrong. My buttons work perfectly fine but it's just the AVAudioPlayer (var Player) that is not allowing the buttons to crash the program and return the error. Any help would be much appreciated (I'm a beginner at Swift).

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var player:AVAudioPlayer = AVAudioPlayer()

    @IBAction func play(_ sender: UIButton) {

        player.play()
    }

    @IBAction func pause(_ sender: UIButton) {
        player.pause()
    }

    @IBAction func replay(_ sender: UIButton) {
       player.currentTime = 0
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

            do{
                let audioPath = Bundle.main.path(forResource: "song", ofType: "mp3")
                try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
            }
            catch{
                //error
            }                                        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }            
}

Solution

  • I write same code project ,but not have any wrong

    My code

    var player:AVAudioPlayer = AVAudioPlayer()
    lazy var btn: UIButton = {
        var btn = UIButton.init(frame: CGRect.init(x: 20, y: 20, width: 60, height: 60))
        btn.backgroundColor = .red
    
        btn.addTarget(self, action: #selector(ViewController.play), for: .touchUpInside)
        return btn
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
    
        self.view.addSubview(btn)
        do{
            let audioPath = Bundle.main.path(forResource: "song", ofType: "mp3")
            try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
        }
        catch{
            //error
        }
    }
    func play() {
        player.play()
    }
    

    please check you this problem

    1.Whether the player is running on the main thread?

    2.song.mp3 is exist and it can playing

    3.Whether the storyboard is in conflict