AVAudioPlayer 在使用调试脚本之前无法播放声音

AVAudioPlayer can't play sound until using debug script

我正在使用 Xcode 7.3.1 和 iOS 9 并且 AVAudioPlayer 播放声音时遇到问题。我已经尝试了所有可能的解决方案,但没有任何效果这是我的代码

        let mp3Url = NSBundle.mainBundle().URLForResource("BCA", withExtension:"mp3")!

        var player = AVAudioPlayer()

        do {
            player = try AVAudioPlayer(contentsOfURL: mp3Url)
            player.prepareToPlay()
            player.play()
        } catch let error as NSError {
            print(error.description)
        }

直到我在 player.play() 处设置断点并使用 po player 才会播放声音。然后会播放声音。

任何想法都会对我有所帮助。

试试这个:

    var player: AVAudioPlayer?

    func playSound(){
        guard let url = Bundle.main.url(forResource: "alert_song", withExtension: "mp3") else {
            print("MP3 resource not found.")
            return
        }

        print("Music to play : \(String(describing: url))")
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            try AVAudioSession.sharedInstance().setActive(true)

            player = try AVAudioPlayer(contentsOf: url)
            guard let player = player else { return }
            player.play()
        } catch let error {
            print(error.localizedDescription)
        }

    }

试试这个:

    var player = AVAudioPlayer() //global variables will otherwise be deadlock

    let mp3Url = NSBundle.mainBundle().URLForResource("BCA", withExtension:"mp3")!

    do {
        player = try AVAudioPlayer(contentsOfURL: mp3Url)
        player.play()
    } catch let error as NSError {
        print(error.description)
    }