diff --git a/src/Plugin.Maui.Audio/AudioRecorder/AudioRecorder.macios.cs b/src/Plugin.Maui.Audio/AudioRecorder/AudioRecorder.macios.cs index 38622c7..345d5fc 100644 --- a/src/Plugin.Maui.Audio/AudioRecorder/AudioRecorder.macios.cs +++ b/src/Plugin.Maui.Audio/AudioRecorder/AudioRecorder.macios.cs @@ -18,8 +18,6 @@ partial class AudioRecorder : IAudioRecorder public AudioRecorder(AudioRecorderOptions audioRecorderOptions) { this.audioRecorderOptions = audioRecorderOptions; - - ActiveSessionHelper.FinishSession(audioRecorderOptions); } @@ -42,6 +40,9 @@ public Task StartAsync(string filePath, AudioRecorderOptions? options = null) audioRecorderOptions = options; } + // Clean up any previous recorder instance + CleanupRecorderResources(); + ActiveSessionHelper.InitializeSession(audioRecorderOptions); var url = NSUrl.FromFilename(filePath); @@ -86,7 +87,12 @@ destinationFilePath is null || ActiveSessionHelper.FinishSession(audioRecorderOptions); - return new FileAudioSource(destinationFilePath); + var audioSource = new FileAudioSource(destinationFilePath); + + // Clean up resources (event unsubscribed on line 86) + CleanupRecorderResources(unsubscribeEvent: false); + + return audioSource; } static readonly NSObject[] keys = new NSObject[] @@ -105,6 +111,22 @@ void Recorder_FinishedRecording(object? sender, AVStatusEventArgs e) finishedRecordingCompletionSource?.SetResult(true); } + void CleanupRecorderResources(bool unsubscribeEvent = true) + { + if (recorder is not null) + { + if (unsubscribeEvent) + { + recorder.FinishedRecording -= Recorder_FinishedRecording; + } + recorder.Dispose(); + recorder = null; + } + + destinationFilePath = null; + finishedRecordingCompletionSource = null; + } + AudioFormatType SharedEncodingToiOSEncoding(Encoding type, bool throwIfNotSupported) { return type switch