I am trying to make the application respond to claps or above normal sound level. For this, I use Swift and SpriteKit. I imported AVFoundation and of course SpriteKit. This is my setup:
let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,
.UserDomainMask, true)
let docsDir = dirPaths[0] as! String
let soundFilePath =
docsDir.stringByAppendingPathComponent("sound.caf")
let soundFileURL = NSURL(fileURLWithPath: soundFilePath)
let recordSettings =
[AVEncoderAudioQualityKey: AVAudioQuality.Min.rawValue,
AVEncoderBitRateKey: 16,
AVNumberOfChannelsKey: 1,
AVSampleRateKey: 44100.0]
let sprite = SKSpriteNode(imageNamed: "Apple_Swift_Logo")
let recorder = AVAudioRecorder(URL: soundFileURL, settings: recordSettings as [NSObject : AnyObject], error: nil)
var impulseAdded = false
I got this code this site .
Further inside GameSceneand didMoveToView():
//sprite
sprite.position = CGPointMake(320, 568)
addChild(sprite)
//recorder; meteringEnabled set to true to allow access to dB levels
recorder.meteringEnabled = true
recorder.record()
And finally, inside the function update():
recorder.updateMeters()
if recorder.averagePowerForChannel(1) > -160 && impulseAdded == false {
sprite.physicsBody?.applyImpulse(CGVector(dx: 0,dy: 100))
impulseAdded = true
}
The sprite remains static. Impulse is not applied. What is my problem?
Literature:
source
share