C# WPF DataGrid Как сделать корректный аудио плеер

Есть WPF Datagrid в котором отображаются специальные аудио файлы. Они туда попадают в процессе работы фабрики и все являются наследниками одного абстрактного класса. На DataGrid есть событие

    private void Row_DoubleClick(object sender, MouseButtonEventArgs e)
    {            
        CurrentSelectedItemIndex = dataGridView1.SelectedIndex;
        StartPlaying();
    }

    private void StartPlaying()
    {
        if (_audioPlayer == null)
        {                
            StartPlayback();
        }
        else
        {                
            StopPlayback();
            Thread.Sleep(200);
            StartPlayback();
        }
    }

    private void StopPlayback()
  {
    if (_audioPlayer != null)
    {
        _audioPlayer.PlaybackStopType = AudioPlayer.PlaybackStopTypes.PlaybackStoppedByUser;
        _audioPlayer.Stop();
    }
  }

    private void StartPlayback()
    {
        if (CurrentSelectedItemIndex !=-1)
        {

            if (_playbackState == PlaybackState.Stopped)
            {
                var item = dataGridView1.Items[CurrentSelectedItemIndex] as AbstractAudioFile;
                _audioPlayer = new Player2(item.filePath);
                _audioPlayer.PlaybackStopType = Player2.PlaybackStopTypes.PlaybackStoppedReachingEndOfFile;
                _audioPlayer.PlaybackStopped += _audioPlayer_PlaybackStopped;
                CurrentPlayItemIndex = CurrentSelectedItemIndex;
                dataGridView1.SelectedIndex = CurrentPlayItemIndex;
                dataGridView1.ScrollIntoView(dataGridView1.Items[CurrentPlayItemIndex]);
                _audioPlayer.TogglePlay(1f);
            }              

        }
    }

    private void _audioPlayer_PlaybackStopped()
    {
        _playbackState = PlaybackState.Stopped;
        if(_audioPlayer.PlaybackStopType == Player2.PlaybackStopTypes.PlaybackStoppedReachingEndOfFile)
        {
            if (CurrentSelectedItemIndex < dataGridView1.Items.Count - 1)
            {
                CurrentSelectedItemIndex = CurrentPlayItemIndex + 1;
            }
            else
            {
                CurrentSelectedItemIndex = 0;
            }
            StartPlaying();
        }
    }

И собственно класс Player2:

    private WaveOutEvent _outputDevice;
    public enum PlaybackStopTypes
    {
        PlaybackStoppedByUser, PlaybackStoppedReachingEndOfFile
    }

    public PlaybackStopTypes PlaybackStopType { get; set; }

    public Player2(string filepath,float volume = 1f)
    {
        _filepath = filepath;            
        _volume = volume;

        if (File.Exists(_filepath))
        {              
            PlayWav();
        }
        else
        {
            Debug.WriteLine($"file: {_filepath} not found!");
        }

    }

    private void PlayWav()
    {
        PlaybackStopType = PlaybackStopTypes.PlaybackStoppedReachingEndOfFile;           

        var audioFile = new AudioFileReader(_filepath);
        _outputDevice = new WaveOutEvent();
        _outputDevice.PlaybackStopped += _outputDevice_PlaybackStopped;
        _outputDevice.Init(audioFile);
    }
    
    public void Play(PlaybackState playbackState, float currentVolumeLevel)
    {
        if(playbackState == PlaybackState.Stopped || playbackState == PlaybackState.Paused)
        {
            _outputDevice.Play();
        }

        _outputDevice.Volume = currentVolumeLevel;
        
    }
    public void TogglePlay(float currentVolume)
    {
        if (_outputDevice != null)
        {
            Play(_outputDevice.PlaybackState, currentVolume);
        }
        else
        {
            Play(PlaybackState.Stopped, currentVolume);
        }
    }
    public void Stop()
    {
        if (_outputDevice != null)
        {
            _outputDevice.Stop();
        }
    }

Если запускать файлы на проигрывание и останавливать кнопкой "стоп" всё ок. Если запускать файлы на проигрывание в режиме один за одним, используя datagrid как плейлист, то также всё ок. Но если пытаться на плейлисте запускать файлы двойным кликом не дожидаясь окончания проигрывания текущего файла, то получается, что файлы начинают воспроизводиться в несколько потоков и selectedindex в datagrid скачет непонятно как. Я ожидаю поведение при котором при двойном клике на любой файл при незаконченном воспроизведении текущего файла, воспроизведение текущего прекратиться и начнётся воспроизведение нового файла и далее вниз по datagrid. Как мне добиться ожидаемого поведения?


Ответы (0 шт):