0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ミニッツリピーターを作る part.2

Posted at

ミニッツリピーターとはなにか

超スーパー高級腕時計に搭載された機能である。
詳細は前回を参照。

https://qiita.com/antk/items/d67d601096161d77f515

前回 print で書いていた鐘の音をサウンドの再生に置き換える。

SEを鳴らす

ミニッツリピーターの生音を取り込んだmp3がどこかにフリー音源として公開されていないか探したが見つからなかった。
mp3のオリジナル音を鳴らすのは今回パスして、iOSに最初から入っているSEでそれっぽいものを鳴らすことにする。ユーザビリティ的には紛らわしいかもしれないが。

// AudioToolboxを使う
import AudioToolbox

// 音を決める
let lowGong:SystemSoundID = 1054

// 音を鳴らす
AudioServicesPlaySystemSound(lowGong)

基本的にこの3つがあればiOS備え付けのSEを鳴らすことができる。
ちなみに上記の 1054 番はガラスのコップを箸で叩いたような音が鳴る。
どんな種類のSEがあるかは以下の記事を参照。

iOSのシステムサウンドを確認する
https://dev.classmethod.jp/articles/ios-systemsound/

一応ぼくは『音を書く→コンパイル』というどんくさい作業で一応全部聴いて音を決めた。
多分もっといい方法があるはず。

実装する

前回の記事のコメント欄でいただいたアドバイスを元にしたリファクタリングも含める。
実機のゴングが鳴るタイミングを参考に遅延処理で調整する。

import UIKit
import AudioToolbox

class ViewController: UIViewController {
  
  override func viewDidLoad() {
    super.viewDidLoad()
  }
  
  @IBAction func actionButton(_ sender: UIButton) {
    
    let now = Date()
    let time = Calendar.current.dateComponents([.hour, .minute], from: now)
    
    // hour を12時間で丸める
    let hour = time.hour! % 12
    // 60分を15分単位に分割した数
    let quarter = time.minute! / 15
    // 15分に満たない残り分数
    let minute = time.minute! % 15

    // 低音ゴング
    let lowGong:SystemSoundID = 1054
    // 高音ゴング
    let highGong:SystemSoundID = 1013
    
    // 第一ゴング
    for _ in 0 ..< hour {
      AudioServicesPlaySystemSound(lowGong)
      
      // 0.5秒待つ
      Thread.sleep(forTimeInterval: 0.5)
    }
    
    // 第二ゴングが鳴る場合遅延処理
    if quarter > 0 {
      Thread.sleep(forTimeInterval: 0.7)
    }
    
    // 第二ゴング
    for _ in 0 ..< quarter {
      AudioServicesPlaySystemSound(highGong)
      // 0.4秒待つ
      Thread.sleep(forTimeInterval: 0.4)
      AudioServicesPlaySystemSound(lowGong)
      
      // 0.5秒待つ
      Thread.sleep(forTimeInterval: 0.5)
    }
    
    // 第三ゴングが鳴る場合遅延処理
    if minute > 0 {
      Thread.sleep(forTimeInterval: 0.7)
    }
    
    // 第三ゴング
    for _ in 0 ..< minute {
      print("ding")
      AudioServicesPlaySystemSound(highGong)

      // 0.5秒待つ
      Thread.sleep(forTimeInterval: 0.5)
    }
  }
}

以上。
コンパイルして鳴らしてみるとわりとそれっぽく聴こえる。
ただこの実装だとボタンを押すたびに処理が走るため、連打するとゴングがいつまでも鳴り止まなくなってしまう。@IBAction の処理が終わるまでは操作を受け付けないという方法が見つからなかったので、もしご存知の方がいれば教えていただけると嬉しいです。

0
1
5

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?