在Win 7上更改程序的音量

时间:2012-04-23 17:00:59

标签: c# pinvoke winmm

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

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上实现相同的脚本,只是为了更改主音量(我不会追求)。

2 个答案:

答案 0 :(得分:6)

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

的Xaml

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Slider Minimum="0" Maximum="10" ValueChanged="ValueChanged"/>
    </Grid>
</Window>

C#

public partial class MainWindow
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> 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的返回值。如果您的代码仍无效,它可能会为您提供线索。

答案 1 :(得分:1)

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

您可以在Larry Osterman's blog article

中找到其使用样本列表

最容易使用的是ISimpleVolume界面。它也在Larry's blog中进行了讨论。