在窗口中更改SYSTEM音量级别

本文关键字:SYSTEM 窗口 | 更新日期: 2023-09-27 18:16:39

我的应用程序需要能够更改声音设备的系统音量级别。我在NAudio中使用C#。我尝试在NAudio中使用CoreAudio-Api,但这在Windows XP中不起作用,但我的程序需要支持XP。请帮助我,我需要使用什么,让我的程序支持XP和最新的Windows。

在窗口中更改SYSTEM音量级别

以下是使用p/Invoke调用的最简单且众所周知的方法:

    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 VolumeControl
    {
       public partial class Form1 : Form
       {
          [DllImport("winmm.dll")]
          public static extern int waveOutGetVolume(IntPtr hwo, out uint dwVolume);
      [DllImport("winmm.dll")]
      public static extern int waveOutSetVolume(IntPtr hwo, uint dwVolume);
      public Form1()
      {
         InitializeComponent();
         // By the default set the volume to 0
         uint CurrVol = 0;
         // At this point, CurrVol gets assigned the volume
         waveOutGetVolume(IntPtr.Zero, out CurrVol);
         // Calculate the volume
         ushort CalcVol = (ushort)(CurrVol & 0x0000ffff);
         // Get the volume on a scale of 1 to 10 (to fit the trackbar)
         trackWave.Value = CalcVol / (ushort.MaxValue / 10);
      }
      private void trackWave_Scroll(object sender, EventArgs e)
      {
         // Calculate the volume that's being set
         int NewVolume = ((ushort.MaxValue / 10) * trackWave.Value);
         // Set the same volume for both the left and the right channels
         uint NewVolumeAllChannels = (((uint)NewVolume & 0x0000ffff) | ((uint)NewVolume << 16));
         // Set the volume
         waveOutSetVolume(IntPtr.Zero, NewVolumeAllChannels);
      }
   }
}

来源:http://www.geekpedia.com/tutorial176_Get-and-set-the-wave-sound-volume.html

此外,如果您希望将其与CoreAudioAPI结合使用,请阅读以下内容:在C#中将主音量从XP更改为Windows 8