0
0

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.

swift辞書「振らた事を検知する」

Posted at

お断り

この記事は自分専用メモなのですごい初歩的な事しか書いていませんがご了承下さい。
確認環境
Interface:Storyboard
Life Cycle:UIKit App Delegate
Language:Swift
◉Use Core Data
__○Host in CloudKit
◉Include Tests

この記事で出来る様になる事

振られた時の処理が書けるよういになる

実装

UIの実装

無し!!

コードの実装

import UIKit
import CoreMotion
import AVFoundation

class ViewController: UIViewController {
    
    let MotionSensor = CMMotionManager()
    var sound:AVAudioPlayer!

    override func viewDidLoad() {
        super.viewDidLoad()
        getAccelerometer()
        sound = try? AVAudioPlayer(contentsOf: URL(fileURLWithPath: Bundle.main.path(forResource: "test", ofType: "wav")!))
        // Do any additional setup after loading the view.
    }
    func get() {
            sound.stop()
            sound.currentTime = 0
            sound.play()
    }
    func getAccelerometer() {
        MotionSensor.accelerometerUpdateInterval = 0.2
        MotionSensor.startAccelerometerUpdates(to: OperationQueue.current!, withHandler: {
            accelerometerData,error in
            let x = accelerometerData!.acceleration.x
            let y = accelerometerData!.acceleration.y
            let z = accelerometerData!.acceleration.z
            let synthetic = (x * x) + (y * y) + (z * z)
            
            if synthetic >= 6 {
                self.get()
            }
        })
    }

}

**let MotionSensor = CMMotionManager()**ではCMMotionManagerのインスタンスMotionSensorを作る
**func getAccelerometer()**この関数内に振られたか調べるプログラムを書いて行く
MotionSensor.accelerometerUpdateInterval = 0.2加速度を確認する間隔を0.2秒ごとに確認する
let x = accelerometerData!.acceleration.xではxの加速度を取得する
**let synthetic = (x * x) + (y * y) + (z * z)**ではx、y、zの加速度を掛け合わせて変数syntheticに代入する
後はif文で一定値を越えたら音を鳴らす関数を呼び出す

細かいところ

めんどくさいので細かい所はappleのリファレンスを見て
https://developer.apple.com/documentation/coremotion

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?