Check if AVAudioPlayer is playing

微笑、不失礼 提交于 2019-12-13 04:32:23

问题


I've been trying to check if the AVAudioPlayer is currently playing, but when I try to do it in anyway it crashes.

I'm using stop button to stop the audio but when there is no audio playing it crashes.

How is it possible to check it in my stopaudio function ?

First I defined :

var audioPlayer = AVAudioPlayer()

I have stop button :

func stopaudio(sender: AnyObject){
    audioPlayer.stop()
}

I tried to check like this :

if audioPlayer.playing{
    audioPlayer.stop()
}

I am using the following code to play the audio :

var soundURL: NSURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("9", ofType: "m4a")!)!
var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: &error)
audioPlayer.prepareToPlay()
audioPlayer.play()

回答1:


The problem was because the AVAudioPlayer hasn't been initialized yet, so what i did to fix it is to initialize it and then stop it.

var soundURL: NSURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("013", ofType: "m4a")!)!
var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: &error)
audioPlayer.stop()



回答2:


Declare a function in the ViewController class:

func tryAudio() {
        do {
            try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: path!))
        } catch {
            //handle errors
        } 

    }

call tryAudio() to initialize the player before player.stop()



来源:https://stackoverflow.com/questions/30302640/check-if-avaudioplayer-is-playing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!