在NAudio中停止播放

问题描述

因此,作为一个学习项目,我一直在使用Terminal.Gui和NAudio构建TUI音乐播放器。 Terminal.Gui得益于API参考,易于使用,但NAudio没有类参考,只有一些示例。

除了基本的GUI外,我还创建了一个WinPlayer类,该类实现了为播放音频文件而编写的IPlayer接口,并且我正在使用构造函数注入方式注入WinPlayer(最终的想法是MacPlayer也是如此)。到目前为止,音频在线程中播放(以防止GUI阻塞),我正在使用互斥锁将音频线程数限制为一个。但是,我的问题是如何停止播放当前的音频线程?从技术上讲,它将是outputDevice.Stop(),但是由于audioFile和outputDevice是局部变量,因此我无法从play方法之外停止它们。

public class WinPlayer : IPlayer
    {
        private static Mutex mut = new Mutex();

        /// <summary>
        /// Method that implements audio playback from a file.
        /// </summary>
        public void PlayAudioFile()
        {
            // Play the audio inside a new thread to prevent our GUI from blocking.
            Task.Run(() =>
            {
                // Block this section of the thread so only one audio file plays at once.
                mut.WaitOne();

                var file = @"C:\MusicSharp\example.mp3";

                try
                {
                    // Load the audio file and select an output device.
                    using var audioFile = new AudioFileReader(file);
                    using var outputDevice = new WaveOutEvent();
                    {
                        outputDevice.Init(audioFile);
                        outputDevice.Play();

                        // Sleep until playback is finished.
                        while (outputDevice.PlaybackState == PlaybackState.Playing)
                        {
                            Thread.Sleep(1000);
                        }
                    }
                }
                catch (System.IO.FileNotFoundException e)
                {
                    System.Console.WriteLine("Error",e);
                }

                // Release the thread.
                mut.ReleaseMutex();
            });
        }
    }

有更好的方法吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)