audioPlayerDidFinishPlaying function in SWIFT

你。 提交于 2020-01-03 01:22:08

问题


I am writing a simple player in swift using the AVFoundation framework. Everything seems to be working except my player keeps playing the same song over and over again. I only have one song in my play list so this makes sense. what I am trying to do is check the audioPlayerDidFinishPlaying flag to make sure it is done playing and then I will make it stop. I am not sure how to implement the call to get the flag here is my code.

    mp3Player?.play()
    **if (mp3Player?.audioPlayerDidFinishPlaying:successfully) {**
    mp3Player?.stop()
 }

the proper way to get the flag in objective c is:

    - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
NSLog(@"audioPlayerDidFinishPlaying");
}

Can anyone explain how to implement the same function in SWIFT? This is my first program in SWIFT. I tried reading about void functions in SWIFT but no luck.

the error I am getting is Cannot convert value of type 'AVAudioPlayer.Type' to expected argument type 'AVAudioPlayer'


回答1:


You can cross check that while start playing the audio numberOfLoops set to 0 and delegate is set to self or controller where your player is playing.

   mp3Player?.numberOfLoops = 0
   mp3Player?.delegate = self

In the same class implement the delegate method of AVAudioPlayer like as shown below.

func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool) {
    //You can stop the audio 
    player.stop()

} 



回答2:


I was able to implement a solution inside the mp3 player class as follows.

func audioPlayerDidFinishPlaying(player: AVAudioPlayer,
    successfully flag: Bool){
        if flag == true {
        ++self.numberOfLoops
        GlobalVariables.NumberOfLoops = numberOfLoops
        numberOfLoopsReq = GlobalVariables.NumberOfLoopsRequired
        player.stop()
        if numberOfLoops <  numberOfLoopsReq {
                // delay before and play
                let delay = GlobalVariables.DelayBeforeSong * Double(NSEC_PER_SEC)// nanoseconds per second
                let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
                dispatch_after(delayTime, dispatch_get_main_queue(),{
                    self.player!.play()
                    }) 
                                             }
                                          }


来源:https://stackoverflow.com/questions/33402854/audioplayerdidfinishplaying-function-in-swift

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