C#控制音量

来源:互联网 发布:一淘和淘宝客同时赚取 编辑:程序博客网 时间:2024/04/30 07:55
using System;  
using System.Collections.Generic;  
using System.ComponentModel;  
using System.Data;  
using System.Drawing;  
using System.Text;  
using System.Windows.Forms;  
using System.Runtime.InteropServices;  
namespace Volume  
{  
    public partial class Form1 : Form  
    {  
        [DllImport("winmm.dll")]  
        public static extern long waveOutSetVolume(UInt32 deviceID, UInt32 Volume);  
        [DllImport("winmm.dll")]  
        public static extern long waveOutGetVolume(UInt32 deviceID, out UInt32 Volume);  
        public Form1()  
        {  
            InitializeComponent();  
        }  
        private void Form1_Load(object sender, EventArgs e)  
        { 
             // 设置滑块值为当前音量的值
             GetVolume() ;
        } 
      
         // 设置当前音量值到滑动条上
        private void GetVolume()  
        {  
            UInt32 d, v;  
            d = 0;  
            long i = waveOutGetVolume(d, out v);  
            UInt32 vleft = v & 0xFFFF;  
            UInt32 vright = (v & 0xFFFF0000) >> 16;  
            trackBar1.Value = (int.Parse(vleft.ToString()) | int.Parse(vright.ToString())) * (this.trackBar1.Maximum - this.trackBar1.Minimum) / 0xFFFF;  
        } 
        // 滑块值改变时,修改音量值
        private void trackBar1_Scroll(object sender, EventArgs e)  
        {  
            UInt32 Value = (System.UInt32)((double)0xffff * (double)trackBar1.Value / (double)(trackBar1.Maximum - trackBar1.Minimum));//先把trackbar的value值映射到0x0000~0xFFFF范围  
            //限制value的取值范围  
            if (Value < 0) Value = 0;  
            if (Value > 0xffff) Value = 0xffff;  
            UInt32 left = (System.UInt32)Value;//左声道音量  
            UInt32 right = (System.UInt32)Value;//右  
            waveOutSetVolume(0, left << 16 | right); //"<<"左移,“|”逻辑或运算  
        }  
    }  
原创粉丝点击