更改轨道NAudio

时间:2019-02-06 14:58:15

标签: c# wpf mvvm slider naudio

我有一个滑块作为音轨时间线的轨迹栏。使用NAudion从网络播放音轨。所有代码均来自NAudio WPF示例。我仅更改了可访问性修饰符。第一次开始播放第一首曲目时一切正常,但是如果更改为下一首曲目,则滑块仍处于开始状态,并且仅在单击``暂停''后再进行播放。< / p>

要完全理解:

第一首曲目-滑块可以移动。

更改为下一首曲目-开头的滑块不动。但是先按“暂停”再按“播放”后,它开始移动。它会立即移至当前正在播放的位置并继续正常操作。接下来的每个曲目都是如此。

PlayerUserControl的VM代码:

public class AudioControlVM : ViewModelBase, IDisposable
    {
        private AudioModel _currentSong;

        public AudioModel CurrentSong { get { return _currentSong; } set { _currentSong = value; RaisePropertyChanged("CurrentSong"); } }

        private string inputPath, songName;
        private string defaultDecompressionFormat;
        public IWavePlayer wavePlayer { get; set; }
        private WaveStream reader;
        public RelayCommand PlayCommand { get; set; }
        public RelayCommand PauseCommand { get; set; }
        public RelayCommand StopCommand { get; set; }
        public DispatcherTimer timer = new DispatcherTimer();
        private double sliderPosition;
        private readonly ObservableCollection<string> inputPathHistory;
        private string lastPlayed;

        public AudioControlVM()
        {
            inputPathHistory = new ObservableCollection<string>();
            PlayCommand = new RelayCommand(() => Play());
            PauseCommand = new RelayCommand(() => Pause());
            StopCommand = new RelayCommand(Stop, () => !IsStopped);
            timer.Interval = TimeSpan.FromMilliseconds(500);
            timer.Tick += TimerOnTick;
        }

        public bool IsPlaying => wavePlayer != null && wavePlayer.PlaybackState == PlaybackState.Playing;

        public bool IsStopped => wavePlayer == null || wavePlayer.PlaybackState == PlaybackState.Stopped;


        public IEnumerable<string> InputPathHistory => inputPathHistory;

        const double SliderMax = 10.0;

        private void TimerOnTick(object sender, EventArgs eventArgs)
        {
            if (reader != null)
            {
                sliderPosition = reader.Position * SliderMax / reader.Length;
                RaisePropertyChanged("SliderPosition");
            }
        }

        public double SliderPosition
        {
            get => sliderPosition;
            set
            {
                if (sliderPosition != value)
                {
                    sliderPosition = value;
                    if (reader != null)
                    {
                        var pos = (long)(reader.Length * sliderPosition / SliderMax);
                        reader.Position = pos; // media foundation will worry about block align for us
                    }
                    RaisePropertyChanged("SliderPosition");
                }
            }
        }

        private bool TryOpenInputFile(string file)
        {
            bool isValid = false;
            try
            {
                using (var tempReader = new MediaFoundationReader(file))
                {
                    DefaultDecompressionFormat = tempReader.WaveFormat.ToString();
                    InputPath = file;
                    isValid = true;
                }
            }
            catch (Exception e)
            {

            }
            return isValid;
        }

        public string DefaultDecompressionFormat
        {
            get => defaultDecompressionFormat;
            set
            {
                defaultDecompressionFormat = value;
                RaisePropertyChanged("DefaultDecompressionFormat");
            }
        }

        public string SongName { get => songName; set
            {
                songName = value;
                RaisePropertyChanged("SongName");
            } }

        public string InputPath
        {
            get => inputPath;
            set
            {
                if (inputPath != value)
                {
                    inputPath = value;
                    AddToHistory(value);
                    RaisePropertyChanged("InputPath");
                }
            }
        }

        private void AddToHistory(string value)
        {
            if (!inputPathHistory.Contains(value))
            {
                inputPathHistory.Add(value);
            }
        }

        public void Stop()
        {
            if (wavePlayer != null)
            {
                wavePlayer.Stop();
            }
        }

        public void Pause()
        {
            if (wavePlayer != null)
            {
                wavePlayer.Pause();
                RaisePropertyChanged("IsPlaying");
                RaisePropertyChanged("IsStopped");
            }
        }

        public void Play()
        {
            if (String.IsNullOrEmpty(InputPath))
            {

                return;
            }
            if (wavePlayer == null)
            {
                CreatePlayer();
            }
            if (lastPlayed != inputPath && reader != null)
            {
                reader.Dispose();
                reader = null;
            }
            if (reader == null)
            {
                reader = new MediaFoundationReader(inputPath);
                lastPlayed = inputPath;
                wavePlayer.Init(reader);
            }
            wavePlayer.Play();
            RaisePropertyChanged("IsPlaying");
            RaisePropertyChanged("IsStopped");
            timer.Start();
        }

        private void CreatePlayer()
        {
            wavePlayer = new WaveOutEvent();
            wavePlayer.PlaybackStopped += WavePlayerOnPlaybackStopped;
            RaisePropertyChanged("wavePlayer");
        }

        private void WavePlayerOnPlaybackStopped(object sender, StoppedEventArgs stoppedEventArgs)
        {

            if (reader != null)
            {
                SliderPosition = 0;
                //reader.Position = 0;
                timer.Stop();
            }
            if (stoppedEventArgs.Exception != null)
            {

            }
            RaisePropertyChanged("IsPlaying");
            RaisePropertyChanged("IsStopped");
        }

        public void PlayFromUrl(string url, string songname)
        {
            Stop();
            inputPath = url;
            SongName = songname;
            Play();
        }

        public void Dispose()
        {
            wavePlayer?.Dispose();
            reader?.Dispose();
        }
    }

播放器的XAML:

    <Grid>
        <StackPanel Orientation="Horizontal">
        <Button Content="Play" Command="{Binding PlayCommand}" VerticalAlignment="Center" Width="75" />
        <Button Content="Pause" Command="{Binding PauseCommand}" VerticalAlignment="Center" Width="75" />
        <Button Content="Stop" Command="{Binding PlayCommand}" VerticalAlignment="Center" Width="75" />

        <Slider VerticalAlignment="Center" Value="{Binding SliderPosition, Mode=TwoWay}" Maximum="10" Width="400" />
            <TextBlock Text="{Binding SongName, FallbackValue=Test}" Foreground="White"/>
        </StackPanel>
    </Grid>
</UserControl>

用于发送新曲目数据的VM代码:

public class AudioModel
{
    public string Artist { get; set; }
    public string SongName { get; set; }
    public int Duration { get; set; }
    public string URL { get; set; }

    public RelayCommand PlayThisAudioCommand
    {
        get;
        private set;
    }

    public AudioModel()
    {
        PlayThisAudioCommand = new RelayCommand(() => PlayThis());
    }

    private void PlayThis()
    {
        if (URL != null)
        {
            TestVM.AudioConrol.PlayFromUrl(URL, SongName);
        }
        else;
    }
}

1 个答案:

答案 0 :(得分:2)

您的计时器似乎有一个多线程问题。事件的顺序似乎是:

第一首曲目

  1. PlayFromUrl()调用Play()开始播放文件,并启动计时器。
  2. 滑块会按预期更新

第二音轨

  1. 调用PlayFromUrl()时:
  2. 调用Stop()(停止wavePlayer,并停止计时器)
  3. 调用Play()(启动wavePlayer,并启动计时器)
  4. 然后 引发wavePlayer.PlaybackStopped事件(由于您先前对wavePlayer.Stop()的调用),该事件调用WavePlayerOnPlaybackStopped(),该事件停止了计时器。

这里的重点是Play()和WavePlayerOnPlaybackStopped()的调用顺序。事件很可能按上述顺序发生-waveWlayer在另一个线程上引发PlaybackStopped事件。

简而言之-WavePlayerOnPlaybackStopped()正在停止您的计时器 Play()启动后,这就是为什么您的滑块没有更新。按“暂停”,然后按“播放”将重新启动计时器,这就是滑块在暂停后开始更新的原因。

您可以通过暂时注释WavePlayerOnPlaybackStopped()中的代码进行测试,这应该可以解决此问题-尽管当轨道到达终点或停止时滑块不会重置为零。

注意:调用wavePlayer.Stop()和wavePlayer.PlaybackStopped事件之间出现延迟的原因是由于nAudio使用专用线程来处理回放。当您调用Stop()时,它必须在实际停止之前完成对当前音频缓冲区的处理-这在大多数情况下会导致几毫秒的延迟。

您可以在WaveOutEvent的DoPlayback方法中看到这一点:https://github.com/naudio/NAudio/blob/master/NAudio/Wave/WaveOutputs/WaveOutEvent.cs#L147