大树下好乘凉

导航

C#调用DLL处理声卡程序

微软封装了大量的Windows的API在.NET Framwork中,但是还是有些文件我们需要使用,而.NET Framwork中并没有方便的提供。用C#调用Windows的Dll文件,能给我们带来很多便利。

    下面的程序是一个发声程序,使用Windows的dll文件实现,能够播放wav声音文件。

    这是实现的源文件SpeakerBeaper.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace HardWaresOperation
{
    public class SpeakerBeeper
    {
        //#region 调用DLL文件判断机器是否有声卡
        //[DllImport("winmm.dll",EntryPoint = "waveOutGetNumdevs")]

        ////waveOutGetNumdevs()方法
        ////当机器有声卡时返回1
        ////没有声卡返回0
        //public static extern int waveOutGetNumdevs();
        //#endregion

        //文件资源
        private string SoundSource = @"C:\Documents and Settings\Administrator\桌面\gc22002a.wav";

        public SpeakerBeeper(string _SoundSource)
        {
            SoundSource = _SoundSource;
        }

        /// <summary>
        /// 检查声卡,播放声音
        /// </summary>
        /// <param name="_SoundSource">声音文件</param>
        /// <returns>播放成功,返回true</returns>
        public bool SpeakerBeep()
        {
            if (SBHelper.waveOutGetNumDevs()!= 0)
            {
                SBHelper.PlaySound(SoundSource, IntPtr.Zero, SBHelper.PlaySoundFlags.SND_FILENAME | SBHelper.PlaySoundFlags.SND_ASYNC);
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

 

   这是辅助的文件SBHelper.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace HardWaresOperation
{
    class SBHelper
    {
        public enum PlaySoundFlags : int
        {
            SND_SYNC = 0x0000,//同步
            SND_ASYNC = 0x0001,//异步
            SND_NODEFAULT = 0x0002,//未找到文件默认为静音
            SND_MEMORY = 0x0004,//声音文件来自内存
            SND_LOOP = 0x0008, //循环播放
            SND_NOSTOP = 0x0010,//不停止目前的播放
            SND_NOWAIT = 0x00002000,//当播放器忙碌时不等待
            SND_ALIAS = 0x00010000, //为已注册的别名时
            SND_ALIAS_ID = 0x00110000, //别名为ID
            SND_FILENAME = 0x00020000, //文件名
            SND_RESOURCE = 0x00040004 //资源名
        }

        #region 调用DLL文件判断机器是否有声卡
        [DllImport("winmm.dll", EntryPoint = "waveOutGetNumDevs")]

        //waveOutGetNumdevs()方法
        //当机器有声卡时返回1
        //没有声卡返回0
        public static extern int waveOutGetNumDevs();
        #endregion

        [DllImport("winmm.dll")]
        //SoundSource声音文件
        //参数hmod是应用程序的实例句柄
        //psFlag播放模式
        public static extern bool PlaySound(string SoundSource, IntPtr hmod,PlaySoundFlags psFlag);
    }
}

posted on 2009-09-07 13:56  大树下好乘凉  阅读(1216)  评论(0编辑  收藏  举报