检查AVAudioPlayer是否正在播放 [英] Check if AVAudioPlayer is playing

查看:133
本文介绍了检查AVAudioPlayer是否正在播放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试检查AVAudioPlayer当前是否正在播放,但是无论如何,当我尝试播放它时,它就会崩溃.

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.

如何在我的stopaudio函数中进行检查?

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

首先我定义了:

var audioPlayer = AVAudioPlayer()

我有停止按钮:

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

我试图这样检查:

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()

推荐答案

问题是因为AVAudioPlayer尚未初始化,所以我要解决的问题是对其进行初始化,然后将其停止.

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()

这篇关于检查AVAudioPlayer是否正在播放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆