简体   繁体   中英

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

I'm new in Swift. I am trying to Run this code but got an error:

Thread 1: EXC_BAD_ACCESS (code=1, address=0x48) a.

Error appears here:

self.player.play()

Can anyone help in this issue?

import UIKit
import AVFoundation

class ViewController: UIViewController {

var player = AVAudioPlayer() override func viewDidLoad() { super.viewDidLoad() do { if let audioPath = Bundle.main.path(forResource: "music", ofType: "mp3") { try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: audioPath)) } } catch { print("ERROR") } self.player.play() }

What you doing with your code is:

  1. Creating an instance of AVAudioPlayer without any data
  2. Trying to create a new instance with some data from music.mp3 file
  3. Playing it

If the audioPath is not correct, then the player is not correctly created: application will use the one without valid data, leading to a crash during playback.

Your code can be written making the player optional , which helps preventing the crash:

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var player: AVAudioPlayer?

    override func viewDidLoad() {
        super.viewDidLoad()

        player = initializePlayer()
        player?.play()
    }

    private func initializePlayer() -> AVAudioPlayer? {
        guard let path = Bundle.main.path(forResource: "music", ofType: "mp3") else {
            return nil
        }

        return try? AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
    }
}

Some changes performed to the code:

  • player is now optional : there is no need to initialize it twice. Plus if the initialization goes well you can use it without problems, otherwise your app won't crash.
  • The play method is now in an optional chain
  • I've moved the initialization of the player in a separate private methods, to maintain the code readable. Feel free to change it, it is just a suggestion.

I've got it. The issue is that the file isn't being coping to my app bundle. To fix it:

  1. Click your project
  2. Click your target
  3. Select Build Phases
  4. Expand Copy Bundle Resources
  5. Click '+' and select your file.

Thanks Denis Hennessy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM