Search code examples
androidxamarinxamarin.androidandroid-audiorecord

How to use AudioRecord.SetRecordPositionUpdateLister in Xamarin?


I'm trying to setup a listener to an audio stream. Here is the (shortened) source:

class AndroidAudioDriver : AudioRecord.IOnRecordPositionUpdateListener
{
    private AudioRecord _recorder;
    private byte[] _audioData;
    private int _bufferSize;
    private Sensor _sensor;

    public AndroidAudioDriver(Sensor sensor, int desiredSampleRate)
    {
        _recorder = new AudioRecord(AudioSource.Mic, SampleRate, ChannelIn.Mono, Encoding.PcmFloat, _bufferSize);
        _recorder.SetRecordPositionUpdateListener(this);
        _recorder.SetPositionNotificationPeriod(_bufferSize / 2);
    }

    public void OnMarkerReached(AudioRecord recorder)
    {
        //not used
    }

    public void OnPeriodicNotification(AudioRecord recorder)
    {
        var count = _recorder.Read(_audioData, 0, _bufferSize / 2);
        var floats = DataConversion.ConvertBytesToFloatsBigEndian(_audioData.Take(count).ToArray());
        NewAudio(_sensor, floats);
    }

    public void Dispose()
    {
        throw new NotImplementedException();
    }
}

My class inherits the IOnRecordPositionUpdateListener. _recorder.SetRecordPositionUpdateListener expects this type as argument, but at runtime I'm getting a "System.InvalidCastException: Specified cast is not valid". I don't understand how to set the update listener in Xamarin, the Android examples are very different and don't seem to apply the same logic.

Thanks.


Solution

  • My class inherits the IOnRecordPositionUpdateListener

    You are implementing the interface, but you need to inherit from Java.Lang.Object.

    Once you do that, make the class public for the ACW (Android Callable Wrapper) that will be generated.

    Remove the public void Dispose() as Java.Lang.Object implements that. If need be, override it and handle disposing any of your resources, like the hardware's Sensor object.

    public class AndroidAudioDriver : Java.Lang.Object, AudioRecord.IOnRecordPositionUpdateListener
    {
    
       ~~~
    }