加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在Win 7上更改程序的音量

发布时间:2020-12-15 07:44:53 所属栏目:百科 来源:网络整理
导读:我想更改程序的音量(而不是主音量).我现在有以下代码: 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);
我想更改程序的音量(而不是主音量).我现在有以下代码:
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

<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的返回值.如果您的代码仍无效,它可能会为您提供线索.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读