我是 Swift 新手。我正在尝试运行此代码,但出现错误:
Thread 1: EXC_BAD_ACCESS (code=1, address=0x48) a.
此处出现错误:
self.player.play()
谁能帮忙解决这个问题吗?
import UIKit import AVFoundationclass 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() }
最佳答案
您对代码所做的事情是:
- 创建 AVAudioPlayer 实例不任何数据
- 尝试使用 music.mp3 文件中的一些数据创建新实例
- 播放
如果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/