I am trying to implement metering for my custom audio recorder for the iOS xamarin forms project. However after turning on metering and polling it, the value is always -160. I am using a physical device, iPhone X to test. Below is my recording code:
public string Record(string filePath)
{
var audioSession = AVAudioSession.SharedInstance();
var err = audioSession.SetCategory(AVAudioSessionCategory.PlayAndRecord);
if (err != null)
{
Console.WriteLine("audioSession: {0}", err);
return err.ToString();
}
err = audioSession.SetActive(true);
if (err != null)
{
Console.WriteLine("audioSession: {0}", err);
return err.ToString();
}
_url = NSUrl.FromFilename(filePath);
//set up the NSObject Array of values that will be combined with the keys to make the NSDictionary
NSObject[] values = new NSObject[]
{
NSNumber.FromFloat (44100.0f), //Sample Rate
NSNumber.FromInt32 ((int)AudioFormatType.LinearPCM), //AVFormat
NSNumber.FromInt32 (2), //Channels
NSNumber.FromInt32 (16), //PCMBitDepth
NSNumber.FromBoolean (false), //IsBigEndianKey
NSNumber.FromBoolean (false) //IsFloatKey
};
//Set up the NSObject Array of keys that will be combined with the values to make the NSDictionary
NSObject[] keys = new NSObject[]
{
AVAudioSettings.AVSampleRateKey,
AVAudioSettings.AVFormatIDKey,
AVAudioSettings.AVNumberOfChannelsKey,
AVAudioSettings.AVLinearPCMBitDepthKey,
AVAudioSettings.AVLinearPCMIsBigEndianKey,
AVAudioSettings.AVLinearPCMIsFloatKey
};
//Set Settings with the Values and Keys to create the NSDictionary
_settings = NSDictionary.FromObjectsAndKeys(values, keys);
//Set recorder parameters
_recorder = AVAudioRecorder.Create(_url, new AudioSettings(_settings), out _error);
if (_error != null)
return _error.ToString();
//Set Recorder to Prepare To Record
_recorder.MeteringEnabled = true;
_recorder.PrepareToRecord();
_recorder.Record();
return "";
}
Below is the code that i poll to log the metering info. It is being called from a threading timer event.
private void ShowMetering()
{
_recorder.UpdateMeters();
Console.WriteLine($"metering:{_recorder.MeteringEnabled} peak power1: {_recorder.PeakPower(0)} avg power1: {_recorder.AveragePower(0)}");
}