您的位置:首页 > 其它

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

2013-01-25 14:20 232 查看
做一个项目,需要播放声音,于是找了几种方法。

首先用的是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();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: