Why doesn't my update () function respond to dB levels?

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:

+4
source share
2 answers

It all comes down to this line of code:

AVNumberOfChannelsKey: 1

In recordSettings.

Then in the function update()it is if recorder.averagePowerForChannel(1) > -160 necessary to change it to this:

if recorder.averagePowerForChannel(0) > -160

, , .

+1

( ).

var error : NSError?
AVAudioSession.sharedInstance.setCategory(AVAudioSessionCategoryPlayAndRecord, error:&error)

if let anError = error {
    NSLog("Error description: \(anError)")
}

var error : NSError?
let recorder = AVAudioRecorder(URL: soundFileURL, settings: recordSettings as [NSObject : AnyObject], error: &error)
if let anError = error {
    NSLog("Error description: \(anError)")
}

var success = recorder.record()
NSLog("recorded successfully? \(success)")
0

Source: https://habr.com/ru/post/1588866/


All Articles