ios - 线程1 :EXC_BAD_ACCESS(code=1, 地址 = 0X48)

标签 ios swift4

我是 Swift 新手。我正在尝试运行此代码,但出现错误:

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

此处出现错误:

self.player.play()

谁能帮忙解决这个问题吗?

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() }

最佳答案

您对代码所做的事情是:

  1. 创建 AVAudioPlayer 实例任何数据
  2. 尝试使用 music.mp3 文件中的一些数据创建新实例
  3. 播放

如果audioPath不正确,则播放器未正确创建:应用程序将使用没有有效数据的播放器,从而导致播放期间崩溃。 p>

您可以编写代码,使播放器成为可选,这有助于防止崩溃:

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))
    }
}

对代码进行的一些更改:

  • player 现在可选:无需初始化两次。另外,如果初始化顺利,您可以毫无问题地使用它,否则您的应用程序不会崩溃。
  • play 方法现在位于可选链
  • 我已将播放器的初始化移至单独的私有(private)方法中,以保持代码的可读性。请随意更改它,这只是一个建议。

关于ios - 线程1 :EXC_BAD_ACCESS(code=1, 地址 = 0X48),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46526759/

相关文章:

ios - 渐变颜色不会根据按钮 isSelected 状态而变化

ios - 如何识别哪个 UITextField 被 textFieldDidChange 更改了

swift - Swift4 转换后 "' init ' is deprecated"警告

ios - 如果不使用,分发配置文件中的 "Enabled Services"会导致 App Store Review 出现问题

ios - PopoverPresentationController 委托(delegate)方法未调用

ios - 使用 Swift 向 ViewController 添加约束

ios - 是否可以在 iOS 上将 AES128 与 GCM 模式一起使用?

swift - 通过 Alamofire 集成 salesforce api?

ios - getter 和 setter 自定义并发队列同步的竞争条件

swift - 无法将 Substring 类型的值转换为预期的参数类型 String - Swift 4