[英]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 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() }
What you doing with your code is: 您对代码执行的操作是:
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. play
method is now in an optional chain play
方法位于可选链中 I've got it. 我懂了。 The issue is that the file isn't being coping to my app bundle.
问题是该文件无法处理我的应用程序捆绑包。 To fix it:
要解决这个问题:
Thanks Denis Hennessy 感谢丹尼斯·轩尼诗
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.