c# - 更改 Windows 中的系统音量级别

标签 c# audio volume naudio

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

最佳答案

这是使用 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#

关于c# - 更改 Windows 中的系统音量级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16894421/

相关文章:

c# - 使用静态 NavigateTo<T> 方法在 Xamarin.Forms 中导航时如何传递参数?

c# - 在子查询上使用 DISTINCT 以删除 Entity Framework 中的重复项

java - 将音量应用于产生静电/噪音的 PCM 样本?

android - Android Audio Recorder的** getMaxAmplitude()**在不同的设备上返回不同的值

c# - System.Text.RegularExpressions.Regex.Matches 的性能特征 - 一个错误?

c# - msbuild/csproj 执行任务问题

java - 如何用 java 中的字节数组编写 WAV 文件?

c++ - 将列出哪些设备

c# - 用于 NAudio 录音的音频电平表

linux - 将 s3fs 作为卷提供给 docker