Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios AVAudioPlayer可以';在使用调试脚本之前,不要播放声音_Ios_Swift_Audio_Avaudioplayer - Fatal编程技术网

Ios AVAudioPlayer可以';在使用调试脚本之前,不要播放声音

Ios AVAudioPlayer可以';在使用调试脚本之前,不要播放声音,ios,swift,audio,avaudioplayer,Ios,Swift,Audio,Avaudioplayer,我在iOS 9上使用Xcode 7.3.1,在AVAudioPlayer上播放声音时遇到问题。我已经尝试了所有可能的解决方案,但我的代码没有任何效果 let mp3Url = NSBundle.mainBundle().URLForResource("BCA", withExtension:"mp3")! var player = AVAudioPlayer() do { player = try AVAudioPlay

我在iOS 9上使用Xcode 7.3.1,在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)
    }

这对我有用!如果我使用player作为全局变量,那么就可以了