简体   繁体   English

线程1:EXC_BAD_ACCESS(代码= 1,地址= 0X48)

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

I'm new in Swift. 我是Swift的新手。 I am trying to Run this code but got an error: 我正在尝试运行此代码,但出现错误:

Thread 1: EXC_BAD_ACCESS (code=1, address=0x48) a. 线程1:EXC_BAD_ACCESS(代码= 1,地址= 0x48)

Error appears here: 错误出现在这里:

self.player.play() 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 创建没有任何数据的AVAudioPlayer实例
  2. Trying to create a new instance with some data from music.mp3 file 尝试使用来自music.mp3文件的一些数据创建新实例
  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. 如果audioPath不正确,则说明播放器创建不正确:应用程序将使用没有有效数据的播放器,从而导致播放过程中崩溃。

Your code can be written making the player optional , which helps preventing the crash: 您可以编写代码使播放器成为optional ,这有助于防止崩溃:

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. player现在是可选的 :无需将其初始化两次。 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 现在, play方法位于可选链中
  • 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 感谢丹尼斯·轩尼诗

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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