jfversluis / Plugin.Maui.Audio

Plugin.Maui.Audio provides the ability to play audio inside a .NET MAUI application
MIT License
257 stars 44 forks source link

Feature request: pause during recording #67

Open davepruitt opened 1 year ago

davepruitt commented 1 year ago

It would be nice to have a "pause" feature on the IAudioRecorder interface so that I can pause and resume recordings.

bijington commented 11 months ago

Having a quick look at the platforms I can't see an obvious option for this on Android

Sl0thie commented 11 months ago

Can you not use the current position and seek to implement this?

bijington commented 11 months ago

Can you not use the current position and seek to implement this?

I don't think AudioRecord offers support for seeking either. I guess we could try stopping and starting a recording and see if that allows us to join 2 clips together.

Sl0thie commented 11 months ago

Sorry for some reason I had playback in mind.

davepruitt commented 11 months ago

So my app is primarily targeting Android, and I went ahead and implemented this feature myself in my own private fork of this repository.

I'll share my solution for Android here. Since I am not currently targeting other operating systems, I haven't made any effort to get this to work on iOS or Windows.

Anyway, here is my Android solution.

  1. In the file IAudioRecorder.shared.cs, I placed the following code in the interface:
void Pause(bool pause);
  1. Next, in the class AudioRecorder found in AudioRecorder.android.cs, I added the following private variable:
private bool is_paused = false;
  1. I then modified the function StartAsync(string filePath) so that it contains the following line of code:
is_paused = false;

The purpose of this is simply to make sure that we set the is_paused flag to false every time we start a recording.

  1. Next, I implemented the Pause function which I placed in the interface in step 1:
public void Pause(bool pause)
{
    is_paused = pause;
}
  1. Finally, I simply wrapped the call to outputStream.write in the WriteAudioDataToFile function in an if-statement, so the main recording loop looks like this:
while (audioRecord.RecordingState == RecordState.Recording)
{
    audioRecord.Read(data, 0, bufferSize);

    if (!is_paused)
    {
        outputStream.Write(data);
    }
}

So, technically this means that loop is still running even when paused, but the key point is that it's not saving any audio data to the temporary file while it is paused. Then, when the user "un-pauses", that data will start writing to the temporary file again.

This should take care of Android.

bijington commented 10 months ago

Thanks for sharing this. Sadly I don't think we have this luxury on iOS or Windows.