WinForm开发遇到播放声音的问题

做一个项目,需要播放声音,于是找了几种方法。

首先用的是Soundplayer,它在.NET 自带的类库 System.Media 下。

Soundplayer这家伙有一个特点就是只能播放一个音频文件,不论你new出多少个Soundplayer,它总是播放最后一个音频。只要其中任何一个Soundplayer被停止,马上就没声音了!

后来就换DirectSound,它需要下载并安装Micrisoft DirectX SDK。

这家伙虽然可以多个音频同时播放,但是,它有一个怪癖,就是只要窗口没有被聚焦,它就Shut up了。

后来又试了AxWindowsMediaPlayer,这个玩意呢它好像只能指定音频路径,但是,我想要直接调用资源文件里面的音频,所以,我抛弃它!

最后,无意中搜到NAudio,于是就开始研究它!

这玩意也是有点毛病,竟然没有循环播放的方法,网上找了老半天也没有人做过这个,倒是不少人抄那篇“用C#和NAudio解码库播放mp3示例”。

只能自己研究了,最终的MyPlayer代码:

	using System.IO;
	using NAudio.Wave;

	partial class MyPlayer {
		WaveOut player;
		WaveFileReader reader;
		WaveStream pcmStream;
		BlockAlignReductionStream blockAlignedStream;

		public Stream Stream {
			set {
				if(reader != null)
					reader.Dispose();
				if(pcmStream != null)
					pcmStream.Dispose();
				if(blockAlignedStream != null)
					blockAlignedStream.Dispose();
				reader = new WaveFileReader(value);
				pcmStream = WaveFormatConversionStream.CreatePcmStream(reader);
				blockAlignedStream = new BlockAlignReductionStream(pcmStream);
				if(player != null)
					player.Dispose();
				player = new WaveOut(WaveCallbackInfo.FunctionCallback());
				player.PlaybackStopped += new System.EventHandler<StoppedEventArgs>(player_PlaybackStopped);
			}
		}

		public MyPlayer(Stream media) {
			Stream = media;
		}

		public MyPlayer() { }

		public int Looping { get; set; }

		int timer;

		public void Play() {
			timer = 0;
			if(player != null && player.PlaybackState == PlaybackState.Playing)
				return;
			if(blockAlignedStream != null) {
				blockAlignedStream.Position = 0;
				player.Init(blockAlignedStream);
				player.Play();
			}
		}

		void player_PlaybackStopped(object sender, StoppedEventArgs e) {
			if(timer >= 0 && (Looping == 0 || Looping < timer)) {
				blockAlignedStream.Position = 0;
				player.Init(blockAlignedStream);
				player.Play();
			}
			timer++;
		}

		public void Stop() {
			timer = int.MinValue;
			if(player != null) {
				player.Stop();
			}
		}

		public void Dispose() {
			if(reader != null)
				reader.Dispose();
			if(pcmStream != null)
				pcmStream.Dispose();
			if(blockAlignedStream != null)
				blockAlignedStream.Dispose();
			if(player != null) {
				player.Stop();
				player.Dispose();
			}
		}
	}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值