LoginSignup
1
1

More than 5 years have passed since last update.

[Swift][AVAudioFoundation] AVAudioPlayer でオーディオデータ再生が終了したらCallbackする

Posted at

オーディオファイルの再生終了を知りたい時はAVAudioPlayerのcompletionHandlerを使用する。

しかし、単純に使用すると再生が終わる前にcompletionHandlerがFireされてしまう。

例えばこんな感じ

completionHandler.swift
 self.audioFilePlayer.scheduleSegment(self.audioFile,
                                      startingFrame:startPlace,
                                      frameCount: frameCount,
                                      at: time,
                                      completionHandler: playCompletion())

func playCompletion(frameCount:Int, startCount:Int)
{
     /* 何か処理*/
}

どのタイミングでcompletionHandlerをFireするかは、completionCallbackTypeを指定することで制御できる。

completionCallbackType.swift
 self.audioFilePlayer.scheduleSegment(self.audioFile,
                                      startingFrame:startPlace,
                                      frameCount: frameCount,
                                      at: time,
                                      completionCallbackType: .dataRendered, // <= これ
                                      completionHandler: playCompletion())

func playCompletion(frameCount:Int, startCount:Int)
{
     /* 何か処理*/
}

上の例では、.dataRenderedを指定し、再生が終わったらcompletionHandlerがFireされるようにしている。
completionCallbackTypeには他にも、以下のようなものがある。

AVAudioPlayerNodeCompletionCallbackType.swift
public enum AVAudioPlayerNodeCompletionCallbackType : Int {


    case dataConsumed

    case dataRendered

    case dataPlayedBack
}

参考
https://developer.apple.com/documentation/avfoundation/avaudioplayernodecompletioncallbacktype?language=objc

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1