Quantcast
Channel: NAudio
Viewing all articles
Browse latest Browse all 5831

New Post: How to Playback audio on a separate Thread

$
0
0
I just changed it to WaveOutEvent, not sure if I'm doing this right though, the Thread starts when I click on buttonPlay, the Thread ends immediately right after it starts, unless I use Sleep for a few seconds, but this is not a problem, what I'm concern is that the audio keeps on playing even when the Thread is finished, is that accurate?, I mean, isn't the audio suppose to stop when the thread is closed?
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using NAudio;
using NAudio.Wave;

namespace NAudioTest
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        public WaveOutEvent waveOutDevice;
        AudioFileReader audioFileReader;

        Thread t;
        
        private void buttonPlay_Click(object sender, EventArgs e)
        {
            if (waveOutDevice == null)
            {
                    t = new Thread(startThread);
                    t.Start();              
            }            
        }


        private void startThread()
        {
            waveOutDevice = new WaveOutEvent();
            audioFileReader = new AudioFileReader(@"C:\Audio\Give Your Heart A Break.mp3");
            waveOutDevice.Init(audioFileReader);
            waveOutDevice.Play();
            Thread.Sleep(3000);
        }

        private void buttonStop_Click(object sender, EventArgs e)
        {
            t.Abort();  
            if (waveOutDevice != null)
            {
                waveOutDevice.Stop();
            }
            if (waveOutDevice != null)
            {
                waveOutDevice.Dispose();
                waveOutDevice = null;
            }
        }

        private void buttonCheckThread_Click(object sender, EventArgs e)
        {
            if (t.IsAlive)
            {
                MessageBox.Show("Is Alive");
            }
            else if (t == null)
            {
                MessageBox.Show("Is Null");
            }
            else
            {
                MessageBox.Show("Other");
            }
        }

    }

}

Viewing all articles
Browse latest Browse all 5831

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>