LoginSignup
1
3

More than 1 year has passed since last update.

Swift でシステムサウンド再生モジュールを作る

Last updated at Posted at 2021-06-24

はじめに

カメラアプリを作っていると、システムサウンドを鳴らしたいときが来ます

録画開始終了時のピコンとポロンを鳴らしたいのです

先駆者様のおかげで実装できたので、モジュール化したものを記載しておきます

先駆者様

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)

まとめ

これで簡単に、それっぽくシステムサウンドが再生できます

1
3
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
3