Reputation: 326
I'm trying to get a decibel value from an AVAudio Recorder. This is my code currently. I have a method to start the recorder, then a method to read the decibel values.
var recorder: AVAudioRecorder!
Recorder defined globally, then used here:
func init_recorder() -> Void
{
let recordersettings = [
AVFormatIDKey: Int(kAudioFormatAppleIMA4),
AVSampleRateKey: 44100,
AVNumberOfChannelsKey: 1 as NSNumber,
AVLinearPCMBitDepthKey: 16,
AVLinearPCMIsFloatKey: false,
AVLinearPCMIsBigEndianKey: false,
//AVEncoderAudioQualityKey: AVAudioQuality.High.rawValue
]
let filename = NSURL(fileURLWithPath: NSTemporaryDirectory().stringByAppendingString("tmp.caf"))
do
{
recorder = try AVAudioRecorder(URL: filename, settings: recordersettings)
recorder.meteringEnabled = true
recorder.prepareToRecord()
recorder.record()
recorder.updateMeters()
}
catch
{
print("error")
}
}
Then to get the decibel values I have
func get_decibels() -> Float
{
recorder.updateMeters()
return recorder.averagePowerForChannel(0)
}
For some reason this is returning a value of -120.0 every time it is called and i'm not too sure why. I have read from http://b2cloud.com.au/tutorial/obtaining-decibels-from-the-ios-microphone/ and a few other stack overflow threads but most of the examples seem to be quite similar to mine.
Any help appreciated, many thanks!
Upvotes: 3
Views: 2763
Reputation: 1113
After you have inited the AVAudioSession
let session = AVAudioSession.sharedInstance()
try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
try session.overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)
try session.setActive(true)
try recorder = AVAudioRecorder(url: getDocumentsDirectory(), settings: settings)
and started recorder
func start() {
recorder?.record()
recorder?.updateMeters()
}
You can get the decibels by calling
let decibels = recorder.averagePower(forChannel: 0)
from -120 (min value) up to 0. Noice level of some cafe for example is -20
here's the more detailed example http://www.mikitamanko.com/blog/2017/04/15/swift-how-to-get-decibels/
Upvotes: 1