每次按下我都会得Thread1:EXC_BAD_ACCESS(code=1, address = 0X48)
一个button
。我检查了我的连接和我的mp3文件" song"是正确的。我不确定是什么错。我的按钮工作得很好,但它只是AVAudioPlayer (var Player)
不允许按钮崩溃程序并返回错误。任何帮助都会非常感激(我是Swift的初学者)。
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player:AVAudioPlayer = AVAudioPlayer()
@IBAction func play(_ sender: UIButton) {
player.play()
}
@IBAction func pause(_ sender: UIButton) {
player.pause()
}
@IBAction func replay(_ sender: UIButton) {
player.currentTime = 0
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
do{
let audioPath = Bundle.main.path(forResource: "song", ofType: "mp3")
try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
}
catch{
//error
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 0 :(得分:0)
我编写了相同的代码项目,但没有任何错误
我的代码
var player:AVAudioPlayer = AVAudioPlayer()
lazy var btn: UIButton = {
var btn = UIButton.init(frame: CGRect.init(x: 20, y: 20, width: 60, height: 60))
btn.backgroundColor = .red
btn.addTarget(self, action: #selector(ViewController.play), for: .touchUpInside)
return btn
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(btn)
do{
let audioPath = Bundle.main.path(forResource: "song", ofType: "mp3")
try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
}
catch{
//error
}
}
func play() {
player.play()
}
请检查这个问题
1.玩家是否在主线程上运行?
2.song.mp3存在且可以播放
3.故事板是否存在冲突