はじめに
カメラアプリを作っていると、システムサウンドを鳴らしたいときが来ます
録画開始終了時のピコンとポロンを鳴らしたいのです
先駆者様のおかげで実装できたので、モジュール化したものを記載しておきます
先駆者様
SystemSound を enum にしておく
1117
とかいう数字を使用時に丸出しにしたくないので、使う SystemSoundID を Enum にしておく
import AVFoundation
enum SystemSound: UInt32 {
case beginVideoRecording = 1117
case endVideoRecording = 1118
var systemSoundID: SystemSoundID {
self.rawValue as SystemSoundID
}
}
システムサウンドの一覧はこちら
どんな音か聞いて確かめたいときは、こちらのアプリが非常に便利です
SystemSoundPlayer を作る
あちこちで使えるように .play
で再生できる Player を作っておきます
import AVFoundation
import Foundation
public class SystemSoundPlayer {
func play(systemSoundID: UInt32) {
var soundIdRing: SystemSoundID = systemSoundID
if let soundUrl = CFBundleCopyResourceURL(CFBundleGetMainBundle(), nil, nil, nil) {
AudioServicesCreateSystemSoundID(soundUrl, &soundIdRing)
AudioServicesPlaySystemSound(soundIdRing)
}
}
func play(systemSound: SystemSound) {
self.play(systemSoundID: systemSound.systemSoundID)
}
}
SystemSoundPlayer を使う
SystemSound を enum にしておいたおかけで、使用時には XCode が補完してくれる
let systemSoundPlayer = SystemSoundPlayer()
systemSoundPlayer.play(systemSound: .beginVideoRecording)
まとめ
これで簡単に、それっぽくシステムサウンドが再生できます