线程 1:EXC_BAD_ACCESS(代码=1,地址=0x48)avaudiofoundation

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

当我尝试 运行 我的代码时,我在上面的代码标题中的

行中收到错误

audioPlayer = try AVAudioPlayer(contentsOf: url)

在我将 Xcode 更新为 Xcode 11 之前,这段代码非常有效,现在使用 swift 5,我不得不更改它,但现在它不起作用.有人可以帮帮我吗?这是我的代码

import UIKit
import AVFoundation

class ViewController: UIViewController, AVAudioPlayerDelegate {

override func viewDidLoad() {
    super.viewDidLoad()

    playAudio()

}

@IBAction func playButton(_ sender: Any) {
playAudio()
}


var indexPath = 0
var listOfTheSongs = ["badLiar.mp3", "cool.mp3", "eastSide.mp3", "fallinAllInYou.mp3", "hateHowMuchILoveYou.mp3", "inMyBlood.mp3", "letMeDownSlowly.mp3", "loveYourself.mp3", "panini.mp3", "rewriteTheStars.mp3", "stiches.mp3", "treatYouBetter.mp3", "wow.mp3"]
 var audioPlayer = AVAudioPlayer()
 var path = Bundle.main.path(forResource: "badLiar.mp3" , ofType: nil , inDirectory: "Songs For Lyric Hunt")!


func playAudio () {

    if path != nil {
        print("path does not equal nil")
        let url = URL(fileURLWithPath: path)
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: url)
            if audioPlayer.isPlaying == true {
            audioPlayer.stop()
            } else {
                audioPlayer.play()
            }
        } catch {
            // couldn't load file :(
            print("counldn't load file :(")
        }
    }else {
        print(" path equals to nil")

        }
    }



}

参考这个,你需要像下面这样初始化你的AVAudioPlayer:

var audioPlayer: AVAudioPlayer!

用上面的行替换你的var audioPlayer = AVAudioPlayer()

这应该可以解决崩溃问题。似乎问题发生在 iOS 13.1

您是否将框架添加到您的项目中? 如果没有,试试这个

在 game/App 的 常规 选项卡中 框架、库和嵌入式内容 单击 + 并输入或搜索 AVFoundation.framework

希望对您有所帮助