Search code examples
androiddot42

Play Audio Track Asynchronously


I've tried to use Xamarin example of audio record/play using the follow code: Example_WorkingWithAudio

At the following Task i have async error:

protected async Task PlayAudioTrackAsync ()
{
    audioTrack = new AudioTrack (
        // Stream type
        Android.Media.Stream.Music,
        // Frequency
        11025,
        // Mono or stereo
        ChannelConfiguration.Mono,
        // Audio encoding
        Android.Media.Encoding.Pcm16bit,
        // Length of the audio clip.
        buffer.Length,
        // Mode. Stream or static.
        AudioTrackMode.Stream);

    audioTrack.Play ();

    await audioTrack.WriteAsync (buffer, 0, buffer.Length);
}

Changed for dot42:

protected async Task PlayAudioTrackAsync()
{
    audioTrack = new AudioTrack (AudioManager.STREAM_MUSIC,11025,
                                 AudioFormat.CHANNEL_OUT_MONO,
                                 AudioFormat.ENCODING_PCM_16BIT,
                                 buffer.Length,
                                 AudioTrack.MODE_STREAM
                                 );
    audioTrack.Play ();
    await audioTrack.WriteAsync(buffer, 0, buffer.Length);
}

How do i change "audioTrack.WriteAsync" ? I've compiler error on this line.


Solution

  • AudioTrack does not have a WriteAsync. For dot42, use this line:

    await Task.Factory.StartNew( () => audioTrack.Write(buffer, 0, buffer.Length) );
    

    I assume this works for Xamarin as well.