如何检查AVAudioPlayer仍在运行?

时间:2022-08-16 21:01:28

I am using AVAudioPlayer ,in my viewdidload method ,initially its running well ,but when i again coming to the same view controller that song starts running mingle with the initial song .

我在我的viewdidload方法中使用AVAudioPlayer,最初运行良好,但是当我再次进入相同的视图控制器时,歌曲开始与初始歌曲混合。

so i am trying to find out is the song running at background?

所以我试图找出那首歌在后台运行?

this is my function ,i am calling this function into the view did load

这是我的函数,我调用此函数进入视图加载

func prepareAudio()
    {
        if audioPlayer.playing
        {
            audioPlayer.stop()
        }
        do
        {

                audioPlayer=try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Kids", ofType: ".mp3")!), fileTypeHint: AVFileTypeMPEGLayer3)
                audioPlayer.delegate=self;
                self.audioPlayer.play()

        }
        catch
        {
            print(error)
        }

    }

but while i am trying to run getting crash here 如何检查AVAudioPlayer仍在运行?

但是我正试图在这里遇到崩溃

help me to find solution for this..

帮我找到解决方案..

2nd try

如何检查AVAudioPlayer仍在运行?

3rd try

如何检查AVAudioPlayer仍在运行?

4th try

如何检查AVAudioPlayer仍在运行?

2 个解决方案

#1


1  

if let audioPlayer = audioPlayer where audioPlayer.playing {
   audioPlayer.stop()
}

// create your audio player and set the delegate etc.

However I would encourage you that if the audioPlayer is not nil, you should not always init the audioPlayer again.

但是我鼓励你,如果audioPlayer不是nil,你不应该总是再次启动audioPlayer。

if let audioPlayer = audioPlayer {
   if audioPlayer.playing {
      audioPlayer.stop()
   }
} else {
   // setup the audioPlayer and set the delegate
}

audioPlayer?.play()

#2


0  

You have to check if the variable is still valid (if not nil)

您必须检查变量是否仍然有效(如果不是nil)

Try this

if ((!audioPlayer) && (audioPlayer.playing == YES))
{
    audioPlayer.stop()
}

#1


1  

if let audioPlayer = audioPlayer where audioPlayer.playing {
   audioPlayer.stop()
}

// create your audio player and set the delegate etc.

However I would encourage you that if the audioPlayer is not nil, you should not always init the audioPlayer again.

但是我鼓励你,如果audioPlayer不是nil,你不应该总是再次启动audioPlayer。

if let audioPlayer = audioPlayer {
   if audioPlayer.playing {
      audioPlayer.stop()
   }
} else {
   // setup the audioPlayer and set the delegate
}

audioPlayer?.play()

#2


0  

You have to check if the variable is still valid (if not nil)

您必须检查变量是否仍然有效(如果不是nil)

Try this

if ((!audioPlayer) && (audioPlayer.playing == YES))
{
    audioPlayer.stop()
}