WinForm开发遇到播放声音的问题,最终采用NAudio实现
				
									
					
					
						|  | 
							admin 2021年2月1日 10:1
								本文热度 5155 | 
					
				 
				做一个项目,需要播放声音,于是找了几种方法。
首先用的是Soundplayer,它在.NET 自带的类库 System.Media 下。
Soundplayer这家伙有一个特点就是只能播放一个音频文件,不论你new出多少个Soundplayer,它总是播放最后一个音频。只要其中任何一个Soundplayer被停止,马上就没声音了!
后来就换DirectSound,它需要下载并安装Micrisoft DirectX SDK。
这家伙虽然可以多个音频同时播放,但是,它有一个怪癖,就是只要窗口没有被聚焦,它就Shut up了。
后来又试了AxWindowsMediaPlayer,这个玩意呢它好像只能指定音频路径,但是,我想要直接调用资源文件里面的音频,所以,我抛弃它!
最后,无意中搜到NAudio,于是就开始研究它!
这玩意也是有点毛病,竟然没有循环播放的方法,网上找了老半天也没有人做过这个,倒是不少人抄那篇“用C#和NAudio解码库播放mp3示例”。
只能自己研究了,最终的MyPlayer代码:
-  BlockAlignReductionStream blockAlignedStream; 
-  if(blockAlignedStream != null) 
-  blockAlignedStream.Dispose(); 
-  reader = new WaveFileReader(value); 
-  pcmStream = WaveFormatConversionStream.CreatePcmStream(reader); 
-  blockAlignedStream = new BlockAlignReductionStream(pcmStream); 
-  player = new WaveOut(WaveCallbackInfo.FunctionCallback()); 
-  player.PlaybackStopped += new System.EventHandler<StoppedEventArgs>(player_PlaybackStopped); 
-  public MyPlayer(Stream media) { 
-  public int Looping { get; set; } 
-  if(player != null && player.PlaybackState == PlaybackState.Playing) 
-  if(blockAlignedStream != null) { 
-  blockAlignedStream.Position = 0; 
-  player.Init(blockAlignedStream); 
-  void player_PlaybackStopped(object sender, StoppedEventArgs e) { 
-  if(timer >= 0 && (Looping == 0 || Looping < timer)) { 
-  blockAlignedStream.Position = 0; 
-  player.Init(blockAlignedStream); 
-  if(blockAlignedStream != null) 
-  blockAlignedStream.Dispose(); 
 
 
该文章在 2021/2/1 10:01:40 编辑过