zoukankan      html  css  js  c++  java
  • [转]c#能发出声音的程序

    第一种方法:
    利用directX,在C#下使用DirectSound实现声音播放 适合directX初学者
    第1步:下载并安装DirectX 9 SDK
    DirectX 9 SDK下载地址:http://msdn.microsoft.com/directx/sdk/
    第2步:建立C#应用程序
    新建一个C#的windows应用程序,名称这里输mydirectXtest。
    解决方案管理器里,右击项目,“添加引用”,选中DirectX和DirectSound
    在Form1.cs里面添加:
    using Microsoft.DirectX;using Microsoft.DirectX.DirectSound;往Form1上面拉一个Label和一个Button,在Button onclick事件里面写入:

    // 建立声音设备 Microsoft.DirectX.DirectSound.Device dev =new Microsoft.DirectX.DirectSound.Device();  dev.SetCooperativeLevel(this,Microsoft.DirectX.DirectSound.CooperativeLevel.Normal);  // 为声音建立二级缓冲区 try{    Microsoft.DirectX.DirectSound.SecondaryBuffer snd =    new Microsoft.DirectX.DirectSound.SecondaryBuffer("http://www.cnblogs.com/NewDrums.wav", dev);//在代码下面有NewDrums.wav文件的详细说明
        // 播放声音    snd.Play(0, Microsoft.DirectX.DirectSound.BufferPlayFlags.Default);}catch (Exception ex){    label1.Text = ex.ToString();}
    详细说明如下:Microsoft.DirectX.DirectSound.Device dev = new Microsoft.DirectX.DirectSound.Device(); ——建立device的类;
    dev.SetCooperativeLevel(this, Microsoft.DirectX.DirectSound.CooperativeLevel.Normal); ——设置CooperativeLevel。因为Windows是多任务的系统,设备不是独占的,所以在使用设备前要为这个设备设置CooperativeLevel-协作模式。调用Device的SetCooperativeLevel方法:其中,第一个参数是一个Control;第二个参数是个枚举类型,用来设置优先级的。
    SecondaryBuffer snd = new Microsoft.DirectX.DirectSound.SecondaryBuffer("http://www.cnblogs.com/NewDrums.wav", dev); —— 开辟缓冲区。声音设备有个自己的缓冲区,叫主缓冲区。系统中,一个设备有唯一的主缓冲区。由于windows是多任务的,所以可以有几个程序同时利用一个设备播放声音,每个程序都自己开辟一个二级缓冲区,放自己的声音。 这里需要注意播放声音的路径,一开始初学者容易把wav声音放到项目里面,在SecondaryBuffer里面直接写“NewDrums.wav”,调试是会显示“应用程序错误”。因为调试的默认文件夹是Debug,需要的声音文件应该放到Debug目录下,用“NewDrums.wav”的格式;或者放在项目下面,用“http://www.cnblogs.com/NewDrums.wav”的格式。
    调试程序,按button就会播放声音了。
    第二种方法?
    1.播放系统自己带的声音:void aa(){System.Media.SystemSounds.Asterisk.Play();}2.播放你的自己的声音文件:using System.Runtime.InteropServices;      //调用系统API
    private void radButton2_Click(object sender, EventArgs e)        {            string strPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;            strPath = strPath + "\\Music\\love.wav";    //系统自己带的声音所在的位置            PlaySound(strPath, IntPtr.Zero, 0);       //用API播放声音文件        }
            [DllImport("winmm.dll", EntryPoint = "PlaySound")]        private static extern bool PlaySound(string pszSound, IntPtr hmod, uint fdwSound);
    最后,送上一个制作屏保的方法,希望大家养成良好的学习习惯,多去CSDN,MSDN上转转。多问问谷姐和度娘。制作屏保:http://www.microsoft.com/china/MSDN/library/enterprisedevelopment/softwaredev/holidayDirectXmas.mspx?mfr=true

  • 相关阅读:
    Centos 7 zabbix 实战应用
    Centos7 Zabbix添加主机、图形、触发器
    Centos7 Zabbix监控部署
    Centos7 Ntp 时间服务器
    Linux 150命令之查看文件及内容处理命令 cat tac less head tail cut
    Kickstart 安装centos7
    Centos7与Centos6的区别
    Linux 150命令之 文件和目录操作命令 chattr lsattr find
    Linux 发展史与vm安装linux centos 6.9
    Linux介绍
  • 原文地址:https://www.cnblogs.com/rongxiaoya/p/2774857.html
Copyright © 2011-2022 走看看