naudio / NAudio

Audio and MIDI library for .NET
MIT License
5.38k stars 1.09k forks source link

.Dispose() doesn't release the process #1055

Open yeatttttt opened 11 months ago

yeatttttt commented 11 months ago

There is my code (gist: https://gist.github.com/sudomarokko/ec87e20e64e40245b7e06803aa6d1af7)

----------------------------------------------------------------------------------------------------
...
private RelayCommand _playAudioCmd;
public IRelayCommand PlayAudioCmd
{
    get { return _playAudioCmd ?? (_playAudioCmd = new RelayCommand(PlayAudio)); }
}
private bool CanPlayAudio()
{
    return !string.IsNullOrWhiteSpace(FilePath);
}
[RelayCommand (CanExecute = nameof(CanPlayAudio))]
private void PlayAudio()
{
    if (!CanPlayAudio())
        return;
    if (!IsPlaying)
    {
        string fullPath = Path.GetFullPath(FilePath);

        var player = new WaveFileReader(FilePath);
        _mediaPlayer.Init(player);
        _mediaPlayer.Play();
        IsPlaying = true;
    }
    else
    {
        _mediaPlayer.Dispose();
        IsPlaying = false;
    }
}
...

----------------------------------------------------------------------------------------------------

...
if (frm.DialogResult)
{
    try
    {
       ...
    }
    finally
    {
        data._mediaPlayer.Dispose();
        data._isPlaying = false;
        File.Delete(data.FilePath);
    }
}
...
----------------------------------------------------------------------------------------------------

Error:

System.IO.IOException: The process cannot access the file 'C:\Users\user\AppData\Local\Temp\record638271093978548587.wav' because it is being used by another process. image

markheath commented 11 months ago

You also need to Dispose the player (your WaveFileReader) once you have finished using it.