【IT168技术文档】
播放Wave文件的代码:
1、添加命名空间:System.Media;
2、添加播放文件的代码:
播放文件一次:
这里调用PlayLooping方法循环播放文件,可以调用Stop方法停止播放。try { SoundPlayer player = new SoundPlayer(EmbeddingWavFiles.Properties.Resources.sound); player.Play(); } catch (Exception ex) { MessageBox.Show(ex.Message + ": " + ex.StackTrace, "Error"); } 这里使用添加的资源来建立一个SoundPlayer类的实例,然后调用它的Play方法播放文件一次。 循环播放: try { SoundPlayer player = new SoundPlayer(EmbeddingWavFiles.Properties.Resources.sound2); if (btnLoopPlay.Text == ("播放")) { player.PlayLooping(); btnLoopPlay.Text = "停止"; } else { player.Stop(); btnLoopPlay.Text = "播放"; } } catch (Exception ex) { MessageBox.Show(ex.Message + ": " + ex.StackTrace, "Error"); }
示例中在建立SoundPlayer的实例时,构造函数的参数类型是System.IO.UnmanagedMemoryStream,除此之外,重载的构造函数还接受字符串,该字符串表示要加载的wave文件的位置。