Farbod Khosrozadeh
Farbod Khosrozadeh

Reputation: 11

Problem with controlling playback speed in C# using the NAudio library

I am trying to use the following code to control the playback speed of an audio object with NAudio library but am running into some problem. How can I alter the play back speed of the media playing object without running into exceptions and bugs, Thanks in advance.

using NAudio.Wave;
using NAudio.Wave.SampleProviders;
 namespace \_2
 {
 
 public partial class Form1 : Form
    {
       private WaveOutEvent outputDevice;
       private AudioFileReader audioFile;
       private VarispeedSampleProvider speedControl;
       public Form1()
      {
           InitializeComponent();
      }

       private void Form1_Load(object sender, EventArgs e)
         {
           outputDevice?.Dispose();
            audioFile?.Dispose();
         }

         private void Button1_Click(object sender, EventArgs e)
         {
             OpenFileDialog openFileDialog = new OpenFileDialog();
             if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                txtFilePath.Text = openFileDialog.FileName;
            }
         }
 
       private void Button2_Click(object sender, EventArgs e)
         {
          if (outputDevice == null)
            {
                outputDevice = new WaveOutEvent();
               outputDevice.PlaybackStopped += OnPlaybackStopped;
             }
            if (audioFile == null)
           {
                 audioFile = new AudioFileReader(txtFilePath.Text);               outputDevice.Init(audioFile);
           }            outputDevice.Play();        }
       private void OnPlaybackStopped(object sender, StoppedEventArgs args)
        {
            outputDevice.Dispose();             outputDevice = null;
            audioFile.Dispose();
           audioFile = null;
        }
       private void Button3_Click(object sender, EventArgs e)
       {
            outputDevice?.Stop();
       }

       private void TrackBar1_Scroll(object sender, EventArgs e)        {
           if (speedControl != null)
           {
            speedControl.PlaybackRate = trackBar1.Value / 10f;
            }
       }
   }
     
 }

Upvotes: 1

Views: 334

Answers (1)

Mark Heath
Mark Heath

Reputation: 49522

Your code does not show how you are calling Init on your outputDevice. But the AudioFileReader needs to be passed into the VarispeedSampleProvider and then that needs to be passed into Init.

Upvotes: 0

Related Questions