C#播放声音的四种方法.docx_第1页
C#播放声音的四种方法.docx_第2页
C#播放声音的四种方法.docx_第3页
C#播放声音的四种方法.docx_第4页
C#播放声音的四种方法.docx_第5页
已阅读5页,还剩33页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

C#播放声音的四种方法 C#播放声音的四种方法 介绍之前首先推荐一个程序员专用搜索引擎-第一种是利用DirectX 1.安装了DirectX SDK(有9个DLL文件)。这里我们只用到MicroSoft.DirectX.dll 和 Microsoft.Directx.DirectSound.dll2.引入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 / 播放声音文件 / / 文件全名 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(); 第三种:引用SoundPlayerSystem.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 lineofDialog.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就可以了。 / Sound.cs / (c) Copyright Jason Clark 2003 / Shows a variety of basic marshalling concepts by making sounds using System; using Wintellect.Interop.Sound; class App public static void Main() / Produce an OK beep Sound.MessageBeep(BeepTypes.Ok); System.Threading.Thread.Sleep(1000); / Ok, now for some circa-1977 si-fi Random rand = new Random(); for( Int32 index = 0; index 7 ; index+ ) Sound.Beep( rand.Next(500)+1000, TimeSpan.FromSeconds(.10); / Pick a wave, any wave Sound.PlayWave( C:WINDOWSMediaBATTLOW.WAV, true ); System.Threading.Thread.Sleep( 2000 ); Sound.StopWave(); namespace Wintellect.Interop.Sound using System.Runtime.InteropServices; using System.ComponentModel; sealed class Sound / Friendly MessageBeep() wrapper public static void MessageBeep(BeepTypes type) if( !MessageBeep( (UInt32) type ) ) Int32 err = Marshal.GetLastWin32Error(); throw new Win32Exception( err ); / Friendly low-level beep wrapper public static void Beep(Int32 frequency, Int32 milliseconds) if(!UnmanagedBeep( (UInt32)frequency, (UInt32)milliseconds ) ) Int32 err = Marshal.GetLastWin32Error(); throw new Win32Exception( err ); / Friendly low-level beep wrapper with TimeSpan public static void Beep(Int32 frequency, TimeSpan duration) Beep( frequency, (Int32)duration.TotalMilliseconds ); / Friendly PlaySound() wrapper for playing wave files public static void PlayWave(String filename, Boolean looped) UInt32 flags = sndAsyncFlag | sndFilenameFlag; if( looped ) flags |= sndLoopFlag; if( !PlaySound( filename, IntPtr.Zero, flags ) ) Int32 err = Marshal.GetLastWin32Error(); throw new Win32Exception( err ); / Friendly PlaySound() wrapper for playing wave files public static void PlayWave(String filename) PlayWave( filename, false ); / Friendly PlaySound() wrapper for stopping wave files public static void StopWave() PlayWave( null ); / static extern methods for making sound through interop DllImport( User32.dll, SetLastError = true ) static extern Boolean MessageBeep(UInt32 beepType); DllImport( Kernel32.dll, EntryPoint = Beep, SetLastError = true) static extern Boolean UnmanagedBeep(UInt32 frequency, UInt32 duration); DllImport( Winmm.dll, CharSet = CharSet.Auto, SetLastError = true) static extern Boolean PlaySound(String filename, IntPtr module, UInt32 flags); / Some private helper values for calling PlaySound const UInt32 sndAsyncFlag = 0x0001; const UInt32 sndLoopFlag = 0x0008; const UInt32 sndFilenameFlag = 0x00020000; private Sound() / Enum for message beep types enum BeepTypes Simple = -1, Ok = 0x00000000, IconHand = 0x00000010, IconQuestion = 0x00000020, IconExclamation = 0x00000030, IconAsterisk = 0x00000040 DllImport(Winmm.dll) public static extern long PlaySound(string name,long module,long flag); DllImport(winmm.dll) private static extern long mciSendString(string lpstrCommand,string lpstrReturnString,long length,long hwndcallback); private string m_MusicName=; private void PlayMusic() m_MusicName=+Tool.ReadInfo(promptmusicfile)+; if(m_MusicName.Length=0) return; try mciSendString(close + m_MusicName, ,0,0); mciSendString(open + m_MusicName, ,0,0); mciSendString(play + m_MusicName , ,0,0); catch private void StopMusic() try mciSendString(close + m_MusicName, ,0,0); catch 播放内存中的WAV文件可以这样: /API定义 private const int SND_ASYNC = 0x1; private const int SND_MEMORY = 0x4; DllImport(winmm.dll) private static extern int sndPlaySoundA(byte lpszSoundName, int uFlags); /将blip1.wav添加入工程并设置为嵌入的资源 /现在是将它读入内存备用 Type t=this.GetType(); System.Reflection.Assembly a=t.Assembly; System.IO.Stream stream=a.GetManifestResourceStream(t.Namespace+.blip1.wav); byte ba=new bytestream.Length; stream.Read(ba,0, ba.Length); stream.Close(); /播放缓存 sndPlaySoundA(ba, SND_MEMORY); 用API函数winmm下的PlaySound播放声音: (一).说明 一个播放音乐的类,要准备好自己的音乐文件,比如:*.mid/*.wav等 (二).步骤 usingSystem; usingSystem.Collections; usingSystem.ComponentModel; usingSystem.Runtime.InteropServices; namespace象棋游戏音效支持类 / /用于播放音乐 / internalclassHelpers Flags publicenumPlaySoundFlags:int SND_SYNC=0x0000,/*playsynchronously(default)*/同步 SND_ASYNC=0x0001,/*playasynchronously*/异步 SND_NODEFAULT=0x0002,/*silence(!default)ifsoundnotfound*/ SND_MEMORY=0x0004,/*pszSoundpointstoamemoryfile*/ SND_LOOP=0x0008,/*loopthesounduntilnextsndPlaySound*/ SND_NOSTOP=0x0010,/*dontstopanycurrentlyplayingsound*/ SND_NOWAIT=0x00002000,/*dontwaitifthedriverisbusy*/ SND_ALIAS=0x00010000,/*nameisaregistryalias*/ SND_ALIAS_ID=0x00110000,/*aliasisapredefinedID*/ SND_FILENAME=0x00020000,/*nameisfilename*/ SND_RESOURCE=0x00040004/*nameisresourcenameoratom*/ DllImport(winmm) publicstaticexternboolPlaySound(stringszSound,IntPtrhMod,PlaySoundFlagsflags); publicclassSound publicstaticvoidPlay(stringstrFileName) switch(strFileName) casestart:strFileName=.soundstart.WAV;break; caseback:strFileName=.soundback.WAV;break; casefall:strFileName=.soundfall.WAV;break; casehuiqi:strFileName=.soundhuiqi.WAV;break; casehuiqiend:strFileName=.soundhuiqiend.WAV;break; casejiangjun:strFileName=.soundjiangjun.WAV;break; casekill:strFileName=.soundkill.WAV;break; casewin:strFileName=.soundwin.WAV;break; casemove:strFileName=.soundmove.WAV;break; casehold:strFileName=.soundhold.WAV;break; caseno:strFileName=.soundno.WAV;break; casepopup:strFileName=.soundpopup.WAV;break; casemayfall:strFileName=.soundmayfall.WAV;break; /调用PlaySound方法,播放音乐 Helpers.PlaySound(strFileName,IntPtr.Zero,Helpers.PlaySoundFlags.SND_FILENAME|Helpers.PlaySoundFlags.SND_ASYNC); (三).使用 1.添加组件(Interop.WMPLib).这个类库VS.Net自带的,默认没有添加进来. 方法:展开项目文件夹,右击引用,添加引用,到Com组件栏,找到添加到项目中. 2.新建一个*.cs文件,把这些代码拷贝进去,全部覆盖即可,并修改上例子中的播放文件名. 就是这样的语句:strFileName=.soundmayfall.WAV;/一定要存在这个音乐文件,否则不能播放 3.如果调用这个方法的地方与此类不在同一个命名空间.要在用的地方打开类的命名空间. 方法:如这个示例类的命名空间应该这样写:usingPlaySound; 最后就可以用了,用法极简单,直接调用此类的方法: Sound.Play(move);/其中参数为音乐文件名(自定义) 相应Blog链接: /chengking/archive/2005/10/07/496627.aspx using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Runtime.InteropServices;namespace MovSysSht internal class CSoundPlay public CSoundPlay() / / TODO: 在此处添加构造函数逻辑 / Flags public enum PlaySoundFlags : int SND_SYNC = 0x0000, /* play synchronously (default) */ SND_ASYNC = 0x0001, /* play asynchronously */ SND_NODEFAULT = 0x0002, /* silence (!default) if sound not found */ SND_MEMORY = 0x0004, /* pszSound points to a memory file */ SND_LOOP = 0x0008, /* loop the sound until next sndPlaySound */ SND_NOSTOP = 0x0010, /* dont stop any currently playing sound */ SND_NOWAIT = 0x00002000, /* dont wait if the driver is busy */ SND_ALIAS = 0x00010000, /* name is a registry alias */ SND_ALIAS_ID = 0x00110000, /* alias is a predefined ID */ SND_FILENAME = 0x00020000, /* name is file name */ SND_RESOURCE = 0x00040004 /* name is resource name or atom */ DllImport(winmm.dll) public static extern bool PlaySound(string szSound, IntPtr hMod, PlaySoundFlags flags); public class Sound public static void Play(string strFileName) CSoundPlay.PlaySound(strFileName, IntPtr.Zero, CSoundPlay.PlaySoundFlags.SND_FILENAME | CSoundPlay.PlaySoundFlags.SND_ASYNC); c#播放mp3控件 C# 播放器空件 的常用方法/*/MediaPlay 9 右击工具箱-选择项(I). - 显示选择工具箱项 - COM组件 - Windows Media Player wmp.dll 添加axWindowsMediaPlayer1.windowlessVideo = false; /设为false后双击屏幕可以全屏axWindowsMediaPlayer1.fullScreen = true; /设播放器全屏播放axWindowsMediaPlayer1.URL = mms:/02/vod/jingwei.wma;axWindowsMediaPlayer1.Ctlcontrols.play(); /播放axWindowsMediaPlayer1.Ctlcontrols.stop(); /停止axWindowsMediaPlayer1.Ctlcontrols.pause(); /暂停axWindowsMediaPlayer1.settings.autoStart = true; /自动播放axWindowsMediaPlayer1.settings.mute = false; /静音axWindowsMediaPlayer1.settings.volume = 100; / 音量int 0 100 100 是最大音量axWindowsMediaPlayer1.currentMedia.duration.ToString();/影片长度axWindowsMediaPlayer1.Ctlcontrols.currentPosition = 30; /当前的播放位置doubleaxWindowsMediaPlayer1.currentMedia.getItemInfo(Title);/标题axWindowsMediaPlayer1.currentMedia.getItemInfo(Author);/作者/*/*/MediaPlay 以前版本右击工具箱-选择项(I). - 显示选择工具箱项 - COM组件 - 浏览(B). - C:WINDOWSsystem32msdxm.ocx - 打开Windows Media Player msdxm.dll 添加label4.Text = axMediaPlayer1.Volume.ToString(); /音量axMediaPlayer1.FileName = mms:/64/vod/jingwei.wma;/文件路径axMediaPlayer1.Play(); /开始播放/*/*/右击工具箱-选择项(I). - 显示选择工具箱项 - COM组件 - RealPlayer G2 Control rmoc3260.dll 添加axRealAudio1.Source = F:mp3hh.mp3; /播放路径axRealAudio1.CanPlayPause(); /Bool 型是否能暂停axRealAudio1.CanPause(); /暂停axRealAudio1.DoPlayPause(); /正在播放的影片暂停播放axRealAudio1.CanPlay(); /Bool是否能播放axRealAudio1.DoPlay(); /播放axRealAudio1.CanStop() /播放是否可以停止axRealAudio1.DoStop(); /播放停止axRealAudio1.SetCenter(true); /按影片原大小播放axRealAudio1.SetFullScreen();/播放器全屏播放影片int place = axRealAudioP.GetPosition();axRealAudio1.DoStop();axRealAudio1.SetCente*(*lse); /拉伸播放 axRealAudio1.SetCenter(true); 按影片原始大小播放axRealAudio1.DoPlay();axRealAudio1.SetPosition(place);nResL = axRealAudio1.GetPosition(); /获得当前影片 的播放进度label1.Text = axRealAudio1.GetTitle(); /获得影片的标题label2.Text = 当前的带宽: + axRealAudio1.GetBandwidthCurrent() / 1024 + KB;/当前影片的当前的带宽label3.Text = 连接的带宽: + axRealAudio1.GetConnectionBandwidth() / 1024 + KB; /当前的连接的带宽怎么获取mp3的头文件信息 比如歌曲名,歌手等呵呵,我以前回答过这个问题,可以看看以前我的得分贴:! /Expert/topic/2349/2349762.xml?temp=.1675074 static void Main(string args) byte b = new byte128; string sTitle; string sSinger; string sAlbum; string sYear; string sComm; FileStream fs = new FileStream(d:mp3.mp3, FileMode.Open); fs.Seek(-128, SeekOrigin.End); fs.Read(b, 0, 128); bool isSet=false; String sFlag = System.Text.Encoding.Default.GetString(b, 0, 3); if (sFlag.CompareTo(TAG)=0) System.Console.WriteLine (Tag is setted!); isSet=true; if (isSet) /get title of song; sTitle = System.Text.Encoding.Default.GetString (b,3,30); System.Console.WriteLine (Title: + sTitle); /get singer; sSinger = System.Text.Encoding.Default.GetString (b,33,30); System.Console.WriteLine (Singer: + sSinger); /get album; sAlbum = System.Text.Encoding.Default.GetString (b,63,30); System.Console.WriteLine (Album: + sAl

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论