2

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

4

1 回答 1

2

这是使用 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 结合使用 - 请阅读:Change master audio volume from XP to Windows 8 in C#

于 2013-08-08T18:18:33.890 回答