从 AVAudioRecorder 获取分贝 [英] Getting Decibels from AVAudioRecorder
问题描述
我正在尝试从 AVAudio Recorder 获取分贝值.这是我目前的代码.我有一种方法可以启动录音机,然后是一种读取分贝值的方法.
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)
}
出于某种原因,每次调用时都会返回 -120.0 的值,我不太确定为什么.我已阅读 http://b2cloud.com.au/tutorial/obtaining-decibels-from-the-ios-microphone/ 和其他一些堆栈溢出线程,但大多数示例似乎与我的非常相似.
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!
推荐答案
在您初始化 AVAudioSession 之后
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)
并启动录音机
func start() {
recorder?.record()
recorder?.updateMeters()
}
您可以通过调用获取分贝
You can get the decibels by calling
let decibels = recorder.averagePower(forChannel: 0)
从 -120(最小值)到 0.例如一些咖啡馆的噪音水平是 -20
from -120 (min value) up to 0. Noice level of some cafe for example is -20
这里是更详细的例子 http://www.mikitamanko.com/blog/2017/04/15/swift-how-to-get-decibels/
这篇关于从 AVAudioRecorder 获取分贝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!