在Win 7上更改程序的音量

我想更改程序的音量(而不是音量)。 我现在有以下代码:

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); private void volumeBar_Scroll(object sender, EventArgs e) { // Calculate the volume that's being set int NewVolume = ((ushort.MaxValue / 10) * volumeBar.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); } 

这仅适用于Win XP,而不适用于Windows 7(也可能不适用于Vista)。 我没有找到任何会在Win 7上实现相同的脚本,只是为了更改主卷(我不会追求)。

你的代码对我来说没问题(有一些调整)。 这是在Windows 7 x64上运行的非常简单的WPF测试应用程序的代码:

XAML

      

C#

 public partial class MainWindow { public MainWindow() { InitializeComponent(); } private void ValueChanged(object sender, RoutedPropertyChangedEventArgs e) { // Calculate the volume that's being set double newVolume = ushort.MaxValue * e.NewValue / 10.0; uint v = ((uint) newVolume) & 0xffff; uint vAll = v | (v << 16); // Set the volume int retVal = NativeMethods.WaveOutSetVolume(IntPtr.Zero, vAll); Debug.WriteLine(retVal); bool playRetVal = NativeMethods.PlaySound("tada.wav", IntPtr.Zero, 0x2001); Debug.WriteLine(playRetVal); } } static class NativeMethods { [DllImport("winmm.dll", EntryPoint = "waveOutSetVolume")] public static extern int WaveOutSetVolume(IntPtr hwo, uint dwVolume); [DllImport("winmm.dll", SetLastError = true)] public static extern bool PlaySound(string pszSound, IntPtr hmod, uint fdwSound); } 

当我启动应用程序并移动滑块时,“音量混合器”中会出现一个额外的音量控制,它与滑块同步地从最小值移动到最大值。

您应该检查waveOutSetVolume的返回值。 如果您的代码仍无效,它可能会为您提供线索。

您可以使用音频会话API IAudioVolume和IAudioSessionNotification来修改当前的应用程序卷,并使用应用程序中的音量滑块来跟踪您的音量。

您可以在Larry Osterman的博客文章中找到他们使用的样本列表

最容易使用的是ISimpleVolume接口。 它也在Larry的博客中讨论过。