using NAudio.Wave; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Windows; using System.Windows.Forms; namespace LiveTools { public class SoundPlay { private readonly WaveOut waveOut = null; /// /// 实例化音频播放类 /// public SoundPlay() { waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()); } /// /// 实例化音频播放类 /// /// public SoundPlay(string path) { waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()); FilePath = path; } /// /// 音频文件地址 /// public string FilePath { get; set; } public event EventHandler OnPlayEnd; /// /// 播放 /// public void Play() { Play(FilePath); } /// /// 播放指定音频 /// /// public void Play(string path) { if (!System.IO.File.Exists(path)) { return; } try { //var ms = System.IO.File.OpenRead(path); var rdr1 = new AudioFileReader(path); waveOut?.Init(rdr1); waveOut?.Play(); while(waveOut.PlaybackState== PlaybackState.Playing) { System.Windows.Forms.Application.DoEvents(); Thread.Sleep(10); } } catch(Exception ex) { } } /// /// 播放状态 /// public PlaybackState PlaybackState { get { return waveOut.PlaybackState; } } /// /// 异步播放指定音频 /// /// public void PlaySync(string path) { if (!System.IO.File.Exists(path)) { return; } Thread th = new Thread(delegate() { Play(path); OnPlayEnd?.Invoke(this,new EventArgs()); }); th.Start(); } /// /// 停止播放 /// public void Stop() { try { waveOut?.Stop(); } catch { } } /// /// 恢复播放 /// public void Resume() { try { waveOut.Resume(); } catch { } } /// /// 暂停播放 /// public void Pause() { try { waveOut.Pause(); } catch { } } /// /// 设置/获取音量,范围为0-1 /// public float Volume { get { return waveOut.Volume; } set { try { waveOut.Volume = value; } catch(Exception ex) { } } } /// /// 销毁数据 /// ~SoundPlay() { try { waveOut.Dispose(); } catch { } } } }