I am very new to developing with Xamarin so I am writing it in C# since this is what I know. I am trying to make a simple Watch application that will record audio and then return the decibel value. I know this is possible since there is a watch app that is doing something like this already but more complex in the App Store. I have found examples on how to record audio with the AVAudioRecorder on iOS but nothing on WatchOS. I haven't tried any other methods since I am so new to this and AVAudioRecorder seems to be the most used.
Here are the 2 issues I am facing:
I have started my audio session with avaudiosession and when I go to use AVAudioRecorder.Create() it says that Create() isn't a part of AVAudioRecorder. Is there something that needs to be imported?
When I go to call the AVAudioRecorder (var record = new AVAudioRecorder) and I try to debug it always crashes the app at this point. If I don't use the "new" and just call for example (_recorder.isMeteringEnabled) it throws an exception of null reference.
All this code is in the main interface controller for the watch and inside its own function.
I am basically following this example: https://github.com/xamarin/recipes/tree/master/Recipes/ios/media/sound/record_sound
Here is some of my code for recording:
// initializing my variables for recording
public partial class InterfaceController : WKInterfaceController
{
public AVAudioPlayer _player;
public AVAudioRecorder _recorder;
}
//my function calling the recording
public void Listen() {
var audioSession = AVAudioSession.SharedInstance();
audioSession.SetCategory(AVAudioSessionCategory.PlayAndRecord);
audioSession.SetActive(true);
string fileName = string.Format("myfile.caf");
string audioFilePath = Path.Combine(Path.GetTempPath(), fileName);
Console.WriteLine("Audio File Path: " + audioFilePath);
NSUrl url = NSUrl.FromFilename(audioFilePath);
Console.WriteLine("Audio File Path: " + url);
//creating values that will be combined with keys to create the dictionary
NSObject[] values = new NSObject[]
{
NSNumber.FromFloat(44100.0f),
NSNumber.FromInt32((int)AudioToolbox.AudioFormatType.LinearPCM),
NSNumber.FromInt32(2),
NSNumber.FromInt32(16),
NSNumber.FromBoolean(false),
NSNumber.FromBoolean(false)
};
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 dictionary
settings = NSDictionary.FromObjectsAndKeys(values, keys);
try {
_recorder = new AVAudioRecorder(); //CRASHES HERE
}
catch (Exception ex) {
Console.WriteLine("{0} Exception", ex);
}
//_recorder.MeteringEnabled = true;
//_recorder.Record();
//_recorder.UpdateMeters();
//var decibels = _recorder.AveragePower(0);
//Console.WriteLine(decibels);
}