我正在开发一个屏幕录制软件,它有音量控制。我在下面粘贴的代码是我控制音量的方式。
static class NativeMethods
{
[DllImport("winmm.dll")]
public static extern int waveOutGetVolume(IntPtr hwo, out uint dwVolume);
[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);
}
//Event for handling volume control
private void VolumeSlider(object sender, RoutedPropertyChangedEventArgs<double> e)
{
// Calculate the volume that's being set
int NewVolume = ((ushort.MaxValue / 10) * (int)slider.Value);
// Set the same volume for both the left and the right channels
uint NewVolumeAllChannels = (((uint)NewVolume & 0x0000ffff) | ((uint)NewVolume << 16));
// Set the volume
NativeMethods.WaveOutSetVolume(IntPtr.Zero, NewVolumeAllChannels);
}
通过查看 Windows 上的音量混合器,我可以看到这设置了应用程序的音量,而不是设备。这很好,因为只有改变应用程序的音量才会改变它正在录制的视频的音量。
现在我想知道是否可以为应用程序的音量创建一个 VU Meter,就像 Windows Volume Mixer 中的音量一样。我曾尝试使用 NAudio 来实现此效果,但我不确定如何或是否可以。我对其他 API 持开放态度。
编辑:我不是在问如何改变音量...我只需要一个正常运行的 VU Meter就像混音器中的开启一样。
最佳答案
不想让这个问题悬而未决,以防其他人偶然发现这个问题。基本上@RickLiddle 评论有答案。我将从所述答案中发布我修改后的代码并尝试解释。试图学习这一点,我已经非常熟悉 NAudio 和 CSCore,所以如果你需要进一步的帮助,请不要犹豫。
class PeakClass
{
static int CurrentProcessID = 0000;
private static void Main(string[] args)
{
//Basically gets your default audio device and session attached to it
using (var sessionManager = GetDefaultAudioSessionManager2(DataFlow.Render))
{
using (var sessionEnumerator = sessionManager.GetSessionEnumerator())
{
//This will go through a list of all processes uses the device
//the code got two line above.
foreach (var session in sessionEnumerator)
{
//This block of code will get the peak value(value needed for VU Meter)
//For whatever process you need it for (I believe you can also check by name
//but I found that less reliable)
using (var session2 = session.QueryInterface<AudioSessionControl2>())
{
if(session2.ProcessID == CurrentProcessID)
{
using (var audioMeterInformation = session.QueryInterface<AudioMeterInformation>())
{
Console.WriteLine(audioMeterInformation.GetPeakValue());
}
}
}
//Uncomment this block of code if you need the peak values
//of all the processes
//
//using (var audioMeterInformation = session.QueryInterface<AudioMeterInformation>())
//{
// Console.WriteLine(audioMeterInformation.GetPeakValue());
//}
}
}
}
}
private static AudioSessionManager2 GetDefaultAudioSessionManager2(DataFlow dataFlow)
{
using (var enumerator = new MMDeviceEnumerator())
{
using (var device = enumerator.GetDefaultAudioEndpoint(dataFlow, Role.Multimedia))
{
Console.WriteLine("DefaultDevice: " + device.FriendlyName);
var sessionManager = AudioSessionManager2.FromMMDevice(device);
return sessionManager;
}
}
}
}
关于c# - VU Meter 像 Windows 音量混合器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34231715/