首页 > 解决方案 > 如何修复线程 1:EXC_BAD_ACCESS (code=1, address=0x58) xcode

问题描述

我正在尝试使用按钮播放一些声音文件,但按下按钮会引发此错误 Thread 1: EXC_BAD_ACCESS (code=1, address=0x58) on line

audioPlayer.play()

我一直在寻找可能的解决方案,但找不到与该错误相关的任何内容,我的代码功能在打印之前运行良好,这是我的完整代码。

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var track: String? = nil
    var audioPlayer = AVAudioPlayer()

    @IBAction func heavyButton(_ sender: Any) {
        track = "H"
        print("heavy machine gun \(track!)")
        reproducirAudio(audio: track!)
        audioPlayer.play()
    }

    func reproducirAudio(audio: String) {
        do {
            print("entro a la funcion de reproducir")
            audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: audio, ofType: "mp3")!))
            audioPlayer.prepareToPlay()
        } catch {
            print(error)
        }
    }
}

标签: iosswiftavaudioplayer

解决方案


我找到了一个解决方案,这是针对 iOS13

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var track: String? = nil
    var audioPlayer: AVAudioPlayer?

@IBAction func heavyButton(_ sender: Any) {
    track = "H"
    print("heavy machine gun \(track!)")
    reproducirAudio(audio: track!)
}

func reproducirAudio(audio: String) {
    let path = Bundle.main.path(forResource: "\(audio).mp3", ofType:nil)!
    let url = URL(fileURLWithPath: path)

    do {
       audioPlayer = try AVAudioPlayer(contentsOf: url)
       audioPlayer?.play()
    } catch {
        // couldn't load file :(
      }
}

推荐阅读