C#播放声音的四种方法

原文:http://www.cnblogs.com/openso2009/archive/2009/09/22/1571606.html

第一种是利用DirectX 
1.安装了DirectX SDK(有9个DLL文件)。这里我们只用到MicroSoft.DirectX.dll 和 Microsoft.Directx.DirectSound.dll
2.引入DirectX 的DLL文件的名字空间:

 using Microsoft.DirectX;
 using Microsoft.DirectX.DirectSound;
3.建立设备
Device dv=new Device();
4.设置CooperativeLevel。因为windows是多任务的系统,设备不是独占的
SecondaryBuffer buf=new SecondaryBuffer(@"snd.wav",dv);
5.开辟缓冲区SecondaryBuffer buf=new SecondaryBuffer(@"snd.wav",dv);

6.接下来就可以播放啦。第一个参数表示优先级别,0是最低的。第2个参数是播放方式,这里是循环播放。
 buf.Play(0,BufferPlayFlags.Looping);
第二种是利用Microsoft speech object Library

/// <summary

        /// 播放声音文件

        /// </summary>

        /// <param name="FileName">文件全名</param>

        public void PlaySound(string FileName)

        {//要加载COM组件:Microsoft speech object Library

            if (!System.IO.File.Exists(FileName))

            {

                return;

            }

            SpeechLib.SpVoiceClass pp = new SpeechLib.SpVoiceClass();

 

            SpeechLib.SpFileStreamClass spFs = new SpeechLib.SpFileStreamClass();

 

            spFs.Open(FileName, SpeechLib.SpeechStreamFileMode.SSFMOpenForRead, true);

            SpeechLib.ISpeechBaseStream Istream = spFs as SpeechLib.ISpeechBaseStream;

            pp.SpeakStream(Istream, SpeechLib.SpeechVoiceSpeakFlags.SVSFIsFilename);

            spFs.Close();

        }

第三种:引用SoundPlayer

System.Media.SoundPlayer sndPlayer = new System.Media.SoundPlayer(Application.StartupPath+@"/pm3.wav");

sndPlayer.PlayLooping();

第4种:利用Windows Media Player
新建一个C#的Windows Form工程(Windows应用程序),并且定义两个菜单按钮(menuItem1,menuItem2)。
  选择菜单中的“工具”中的“自定义工具箱(添加/移除工具箱项)”,在自定义工具箱的窗口中,点击展开“COM 组件”项,选中“Window Media Player”选项。确定后在“工具箱”中便会出现“Windows Media Player”这一项,然后再将其拖至Form上,调整大小,系统在“引用”中自动加入了对此dll的引用,AxMediaPlayer就是我们使用的Namespace与class。
  在属性栏中设置好此控件的一些属性,为了方便,这里我把AutoStart设置成为true(其实默认是true),只要FileName被设置(打开了文件),则文件将会自动播放。完整代码如下:

private void menuItem1_Click(object sender, System.EventArgs e)
{
OpenFileDialog ofDialog = new OpenFileDialog();
ofDialog.AddExtension = true;
ofDialog.CheckFileExists = true;
ofDialog.CheckPathExists = true;



//the next sentence must be in single line
ofDialog.Filter = "VCD文件(*.dat)|*.dat|Audio文件(*.avi)|*.avi
  |WAV文件(*.wav)|*.wav|MP3文件(*.mp3)|*.mp3|所有文件 (*.*)|*.*";



ofDialog.DefaultExt = "*.mp3";
if(ofDialog.ShowDialog() == DialogResult.OK)
{
// 2003一下版本 方法 this.axMediaPlayer1.FileName = ofDialog.FileName;
this.axMediaPlayer1.URL= ofDialog.FileName;//2005用法

}
}



  这里使用的是微软的播放器,大家也可以试试Winamp的控件,如果你只需要播放声音而不需要显示,你只要把AxMediaPlayer的Visible属性设置为false就可以了。


using System;
using System.Runtime.InteropServices; 
using System.Text; 
using System.IO ; 
namespace clsMCIPlay
{
 /// <summary>
 /// clsMci 的摘要说明。
 /// </summary>
 public class clsMCI
 {
  public clsMCI()
  {
   //
   // TODO: 在此处添加构造函数逻辑
   //
  }

  //定义API函数使用的字符串变量 
  [MarshalAs(UnmanagedType.ByValTStr,SizeConst=260)]
  private string Name = "" ;
  [MarshalAs(UnmanagedType.ByValTStr,SizeConst=128)]
  private string durLength = "" ;
  [MarshalAs(UnmanagedType.LPTStr,SizeConst=128)]
  private string TemStr ="";
  int ilong;
  //定义播放状态枚举变量
  public enum State
  {
   mPlaying = 1,
   mPuase = 2,
   mStop = 3
  };
  //结构变量
  public struct structMCI 
  {
   public bool bMut;
   public int iDur;
   public int iPos;
   public int iVol;
   public int iBal;
   public string iName;
   public State state;
  };

  public structMCI mc =new structMCI() ;

  //取得播放文件属性
  public string FileName
  {
   get
   {
    return mc.iName;
   }
   set
   {
    //ASCIIEncoding asc = new ASCIIEncoding(); 
    try
    {
     TemStr =""; 
     TemStr = TemStr.PadLeft(127,Convert.ToChar(" "));
     Name = Name.PadLeft(260,Convert.ToChar(" ")) ;
     mc.iName = value; 
     ilong = APIClass.GetShortPathName(mc.iName,Name, Name.Length);
     Name = GetCurrPath(Name);
     //Name = "open " + Convert.ToChar(34) + Name + Convert.ToChar(34) + " alias media";
     Name = "open " + Convert.ToChar(34) + Name + Convert.ToChar(34) + " alias media";
     ilong = APIClass.mciSendString("close all", TemStr, TemStr.Length , 0);
     ilong = APIClass.mciSendString( Name, TemStr, TemStr.Length, 0);
     ilong = APIClass.mciSendString("set media time format milliseconds", TemStr, TemStr.Length , 0);
     mc.state = State.mStop; 
    }
    catch
    {
     MessageBox.Show("出错错误!"); 
    }
   }
  }
  //播放
  public void play()
  {
   TemStr = "";
   TemStr = TemStr.PadLeft(127,Convert.ToChar(" "));
   APIClass.mciSendString("play media", TemStr, TemStr.Length , 0);
   mc.state = State.mPlaying ;
  }
  //停止
  public void StopT()
  {
   TemStr = "";
   TemStr = TemStr.PadLeft(128,Convert.ToChar(" "));
   ilong = APIClass.mciSendString("close media", TemStr, 128, 0);
   ilong = APIClass.mciSendString("close all", TemStr, 128, 0);
   mc.state = State.mStop ; 
  }

  public void Puase()
  {
   TemStr = "";
   TemStr = TemStr.PadLeft(128,Convert.ToChar(" "));
   ilong = APIClass.mciSendString("pause media", TemStr, TemStr.Length, 0);
   mc.state = State.mPuase ; 
  }
  private string GetCurrPath(string name)
  {
   if(name.Length <1) return ""; 
   name = name.Trim();
   name = name.Substring(0,name.Length-1);
   return name;
  }
  //总时间
  public int Duration
  {
   get
   {
    durLength = "";
    durLength = durLength.PadLeft(128,Convert.ToChar(" ")) ;
    APIClass.mciSendString("status media length", durLength, durLength.Length, 0);
    durLength = durLength.Trim();
    if(durLength == "") return 0;
    return (int)(Convert.ToDouble(durLength) / 1000f); 
   }
  }

  //当前时间
  public int CurrentPosition
  {
   get
   {
    durLength = "";
    durLength = durLength.PadLeft(128,Convert.ToChar(" ")) ;
    APIClass.mciSendString("status media position", durLength, durLength.Length, 0);
    mc.iPos = (int)(Convert.ToDouble(durLength) / 1000f);
    return mc.iPos;
   }
  }
 }

 public class APIClass
 {
  [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
  public static extern int GetShortPathName (
   string lpszLongPath,
   string shortFile,
   int cchBuffer
  );

  [DllImport("winmm.dll", EntryPoint="mciSendString", CharSet = CharSet.Auto)]
  public static extern int mciSendString (
   string lpstrCommand,
   string lpstrReturnString,
   int uReturnLength,
   int hwndCallback
  );
 }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值