How do you remove AVAudioPlayer when the FinishedPlaying event is fired?

I use AVAudioPlayer to play the sound when the user enters a string into a UITableView. If they click on the line again, the player stops and settles down, and if they listen to the song before it ends, the FinshedPlaying handler will position the player.

The problem I am facing is that when I try to get rid of the player in the FinishedPlaying handler, I get an error message:

System.ObjectDisposedException: player object was Dispose () d during the callback it ruined the state of the program

Here's the code, any idea what I'm doing wrong?

void HandleOnRequestPlayMusic (object sender, UrlEventArgs e) { var url = Utils.UrlFromString(e.Url); string oldUrl = ""; if (musicPlayer != null) { oldUrl = musicPlayer.Url.AbsoluteString; KillAudioPlayer(); // no problems killing the audio player from here } if (oldUrl != url.AbsoluteString) { musicPlayer = AVAudioPlayer.FromUrl(url); musicPlayer.FinishedPlaying += HandleAudioFinished; musicPlayer.Play(); } } void HandleAudioFinished (object sender, AVStatusEventArgs e) { KillAudioPlayer(); // killing audio player from here causes app to crash } void KillAudioPlayer () { if (musicPlayer != null) { InvokeOnMainThread(() => { musicPlayer.Stop(); musicPlayer.FinishedPlaying -= HandleAudioFinished; musicPlayer.Dispose(); musicPlayer = null; }); } } 
+4
source share
1 answer

Do not use InvokeOnMainThread because InvokeOnMainThread waits for the input to complete before returning to the caller. This is why your Dispose call happens while you are still inside the KillAudioPlayer call, inside the HandleAudioFinished .

Instead, use BeginInvokeOnMainThread , which will schedule your cleanup action in the main thread, but immediately return to your KillAudioPlayer function, letting it end.

+4
source

Source: https://habr.com/ru/post/1482637/


All Articles