1
1

【Swift5】SystemSoundを繰り返し連続で再生する

Posted at

システムサウンド(効果音)を連続で鳴らす方法について紹介する。
同じ方法でバイブレーションを再生することもできる。

var counter = 3
func soundCallback(sID: SystemSoundID) {
        counter -= 1
        if counter > 0 {
            Thread.sleep(forTimeInterval: 0.5)
            AudioServicesPlaySystemSound(sID)
        } else {
            AudioServicesRemoveSystemSoundCompletion(sID)
        }
    }
    
func alarmStart() {
    let soundID:SystemSoundID = 1036
    AudioServicesAddSystemSoundCompletion(soundID, nil, nil, { (soundID, _) in
        // Convert to function pointer
        ContentView().soundCallback(sID: soundID)
    }, nil)
    AudioServicesPlaySystemSound(soundID)
}

alarmStart関数を呼び出せば、3回システムサウンドが再生される。

AudioServicesAddSystemSoundCompletionを使うと、第4引数で指定したコールバック関数がシステムサウンドの再生が終了したときに呼び出されるため、これを利用することで繰り返しサウンドを再生することができる。

下から2行目のAudioServicesPlaySystemSound(soundID)は、1回目の再生であり、これ以降はsoundCallback関数が呼び出される。counterが0になったところで、AudioServicesRemoveSystemSoundCompletionでコールバックを解除する。

ちなみに、音の種類はSystemSoundIDで指定することができる。以下の記事を参考にすると良い。

参考

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