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; }); } }
source share