使用C#发声(整理)

   由于C#中没有发声的元件,所以要实现此目的需要调用系统的API函数,本文只收录的了如何在window下实现的例子,没有包含非window的操作系统。

     下面是代码:

                     using System.Runtime.InteropServices

                     //在C#中调用winAPI函式

                      [DllImport("winmm.dll" , EntryPoint="PlaySound")]

                     public static extern int PlaySound(string lpxzName, int hModul, int dwFlags);

                     //如何使用PlaySound()函式

                     int  SND_ASYNC = 0X1;

                      int SND_FileNAME = 0X20000;

                     int  SND_LOOP = 0X8;

                     //运行PlaySound函数

                    PlaySound("音频文件名.wav", 0,  SND_ASYNC|SND_FileName|SND_LOOP);

      如果音频文件过大,从而造成系统资源紧张的问题则需另一些方法解决。如分割文件以及建立缓冲区的方法。

        如下:

         //声明一些API函数的调用

         [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")+"/"";    //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{}
                               }

                下面的代码是在内存中建立缓冲机制的方法实例:

                              //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 byte[stream.Length];
                         stream.Read(ba,0, ba.Length);
                          stream.Close();

                        //播放缓存
                         sndPlaySoundA(ba, SND_MEMORY);

    以下是对PlaySound和mcisendstring的说明:

 winmm.dll中对PlaySound的说明:
Platforms: Win 32s, Win 95/98, Win NT PlaySound plays a waveform sound through the speakers. This sound could be a .wav file, a system event sound (such as the system startup sound), or a sound resource stored in an application. Note that when the function needs to play an application resource or a RAM-loaded sound, Visual Basic users must use the alternate declare of the function in order to pass the numeric identifier of the sound instead of a string. The function returns 0 if an error occured, or a non-zero value if successful.
对mciSendString的说明:
mciGetErrorString obtains a textual description of an error raised by another Media Control Interface (MCI) function. Typically these errors are not the fault of the program. Rather, they are caused by "problems" with the device (for example, the MIDI driver is currently being used by another program, so your program's attempt to open it failed). The messages retrieved by this function are sufficient to tell the user what caused the error. 

  ps:随手记录的一段代码,javascrip中实现定时页面刷新及执行一些操作

            可以在javascript中用window.setInterval()来定时的刷新页面,或者使用Meta Refresh来定时刷新,如(<meta http-equiv="refresh" content="1000; url=www.csdn.net">)

             window.setInterval() 的实现:

    <script language="JavaScript">
    function MainP()
    {
        window.setInterval(RefreshPage,30000);
    }

    function RefreshPage()
    {
        window.FormName.submit();
    }
</script>

FormName为按钮等控件所在的Form   的ID

来源:

       http://community.csdn.net/Expert/topic/2697/2697981.xml?temp=.9674799

       http://community.csdn.net/Expert/topic/3249/3249704.xml?temp=2.178371E-03

       http://community.csdn.net/Expert/topic/3713/3713058.xml?temp=.8741266
       

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#使用 waveOut 发声可以通过以下步骤实现: 1. 引用 Windows API 函数库 winmm.dll,使用以下语句: ```csharp [DllImport("winmm.dll")] static extern int waveOutOpen(out IntPtr hWaveOut, uint uDeviceID, ref WAVEFORMATEX lpFormat, WaveCallback dwCallback, IntPtr dwInstance, uint dwFlags); ``` 2. 定义 WAVEFORMATEX 结构体,用于设置音频格式: ```csharp [StructLayout(LayoutKind.Sequential, Pack = 2)] struct WAVEFORMATEX { public short wFormatTag; public short nChannels; public int nSamplesPerSec; public int nAvgBytesPerSec; public short nBlockAlign; public short wBitsPerSample; public short cbSize; } ``` 3. 创建音频缓冲区,使用以下语句: ```csharp IntPtr hWaveOut; // waveOut 句柄 WAVEFORMATEX format = new WAVEFORMATEX { wFormatTag = 1, nChannels = 1, nSamplesPerSec = 8000, nAvgBytesPerSec = 8000, nBlockAlign = 1, wBitsPerSample = 8, cbSize = 0 }; waveOutOpen(out hWaveOut, 0, ref format, null, IntPtr.Zero, 0); ``` 4. 将音频数据写入缓冲区,使用以下语句: ```csharp [DllImport("winmm.dll")] static extern int waveOutPrepareHeader(IntPtr hWaveOut, IntPtr lpWaveOutHdr, uint uSize); [DllImport("winmm.dll")] static extern int waveOutWrite(IntPtr hWaveOut, IntPtr lpWaveOutHdr, uint uSize); byte[] buffer = new byte[8000]; IntPtr hBuffer = Marshal.AllocHGlobal(buffer.Length); Marshal.Copy(buffer, 0, hBuffer, buffer.Length); IntPtr hHeader = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WAVEHDR))); WAVEHDR header = new WAVEHDR { lpData = hBuffer, dwBufferLength = (uint)buffer.Length, dwBytesRecorded = 0, dwUser = IntPtr.Zero, dwFlags = 0, dwLoops = 0, lpNext = IntPtr.Zero, reserved = IntPtr.Zero }; Marshal.StructureToPtr(header, hHeader, false); waveOutPrepareHeader(hWaveOut, hHeader, (uint)Marshal.SizeOf(typeof(WAVEHDR))); waveOutWrite(hWaveOut, hHeader, (uint)Marshal.SizeOf(typeof(WAVEHDR))); ``` 以上就是使用 waveOut 在 C#发声的基本步骤,具体可以根据实际需求进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值