Initial version

This commit is contained in:
EonaCat 2025-07-17 21:29:06 +02:00
parent adda8786f8
commit 0181b0c3b8
31 changed files with 2056 additions and 123 deletions

91
.gitignore vendored
View File

@ -2,7 +2,7 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
@ -14,9 +14,6 @@
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
@ -24,14 +21,10 @@ mono_crash.*
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
@ -45,10 +38,9 @@ Generated\ Files/
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
# NUNIT
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
@ -63,9 +55,6 @@ project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
@ -91,7 +80,6 @@ StyleCopReport.xml
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
@ -133,6 +121,9 @@ _ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
@ -143,11 +134,6 @@ _TeamCity*
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
@ -195,8 +181,6 @@ PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
@ -221,14 +205,12 @@ BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
!*.[Cc]ache/
# Others
ClientBin/
@ -272,9 +254,6 @@ ServiceFabricBackup/
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
@ -295,17 +274,6 @@ node_modules/
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
@ -321,6 +289,10 @@ paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush personal settings
.cr/personal
@ -362,53 +334,10 @@ ASALocalRun/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml
# ---> VisualStudioCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix

View File

@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\EonaCat.VolumeMixer\EonaCat.VolumeMixer.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,170 @@
using EonaCat.VolumeMixer.Managers;
using EonaCat.VolumeMixer.Models;
using System;
using System.Threading.Tasks;
class Program
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
[STAThread]
static async Task Main()
{
// Playback management example
using (var volumeMixer = new VolumeMixerManager())
{
try
{
// Get all audio PLAYBACK devices
var devices = await volumeMixer.GetAudioDevicesAsync(DataFlow.Output);
Console.WriteLine($"Found {devices.Count} playback devices:");
foreach (var device in devices)
{
Console.WriteLine($"- {device.Name} (Default: {device.IsDefault})");
Console.WriteLine($" Volume: {await device.GetMasterVolumeAsync():P0}");
Console.WriteLine($" Muted: {await device.GetMasterMuteAsync()}");
device.Dispose();
}
// Default playback device
using (var defaultDevice = await volumeMixer.GetDefaultAudioDeviceAsync(DataFlow.Output))
{
if (defaultDevice != null)
{
Console.WriteLine($"\nDefault playback device: {defaultDevice.Name}");
// Get all audio sessions
var sessions = await defaultDevice.GetAudioSessionsAsync();
Console.WriteLine($"Active sessions: {sessions.Count}");
foreach (var session in sessions)
{
Console.WriteLine($"- {session.DisplayName} ({await session.GetProcessNameAsync()})");
Console.WriteLine($" Volume: {await session.GetVolumeAsync():P0}");
Console.WriteLine($" Muted: {await session.GetMuteAsync()}");
session.Dispose();
}
}
// Example Set volume of default device
if (defaultDevice != null)
{
// Unmute the device if it is muted
if (await defaultDevice.GetMasterMuteAsync())
{
Console.WriteLine("Unmuting default playback device...");
await defaultDevice.SetMasterMuteAsync(false);
}
Console.WriteLine($"\nSetting default playback device volume to 1%");
bool success = await defaultDevice.SetMasterVolumeAsync(0.1f);
// Log the current volume
Console.WriteLine($"Current volume: {await defaultDevice.GetMasterVolumeAsync():P0}");
for (int i = 0; i < 50; i++)
{
if (await defaultDevice.GetMasterVolumeAsync() >= 1f)
{
break;
}
// Increment volume by 2% each step
success = await defaultDevice.StepUpAsync();
Console.WriteLine($"Current step volume: {await defaultDevice.GetMasterVolumeAsync():P0}");
}
if (success)
{
Console.WriteLine("Volume increased by 95% successfully.");
}
else
{
Console.WriteLine("Failed to increase volume.");
}
// Toggle mute
// bool currentMute = await defaultDevice.GetMasterMuteAsync();
// success = await defaultDevice.SetMasterMuteAsync(!currentMute);
// Console.WriteLine($"Mute toggled: {success}");
}
else
{
Console.WriteLine("No default playback device found");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
// Microphone management example
using (var micManager = new MicrophoneManager())
{
try
{
// Get all microphones
var microphones = await micManager.GetMicrophonesAsync();
Console.WriteLine($"Found {microphones.Count} microphones:");
foreach (var mic in microphones)
{
Console.WriteLine($"- {mic.Name} (Default: {mic.IsDefault})");
Console.WriteLine($" Volume: {await mic.GetMasterVolumeAsync():P0}");
Console.WriteLine($" Muted: {await mic.GetMasterMuteAsync()}");
mic.Dispose();
}
// Default microphone
using (var defaultMic = await micManager.GetDefaultMicrophoneAsync())
{
Console.WriteLine($"\nSetting default microphone volume to 1%");
bool success = await defaultMic.SetMasterVolumeAsync(0.1f);
// Log the current volume
Console.WriteLine($"Current volume: {await defaultMic.GetMasterVolumeAsync():P0}");
for (int i = 0; i < 50; i++)
{
if (await defaultMic.GetMasterVolumeAsync() >= 1f)
{
break;
}
// Increment volume by 2% each step
success = await defaultMic.StepUpAsync();
Console.WriteLine($"Current step volume: {await defaultMic.GetMasterVolumeAsync():P0}");
}
if (success)
{
Console.WriteLine("Volume increased by 95% successfully.");
}
else
{
Console.WriteLine("Failed to increase volume.");
}
}
Console.WriteLine($"Default mic volume: {await micManager.GetMicrophoneVolumeAsync():P0}");
Console.WriteLine($"Default mic muted: {await micManager.GetMicrophoneMuteAsync()}");
// Set microphone volume to 60%
bool result = await micManager.SetMicrophoneVolumeAsync(0.6f);
Console.WriteLine($"Set microphone volume to 60%: {result}");
// Set specific microphone by name
result = await micManager.SetMicrophoneVolumeByNameAsync("USB", 0.7f);
Console.WriteLine($"Set USB microphone volume to 70%: {result}");
}
catch (Exception exception)
{
Console.WriteLine($"Error: {exception.Message}");
}
}
}
}

31
EonaCat.VolumeMixer.sln Normal file
View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EonaCat.VolumeMixer", "EonaCat.VolumeMixer\EonaCat.VolumeMixer.csproj", "{11B9181D-7186-4D81-A5D3-4804E9A61BA6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.VolumeMixer.Tester", "EonaCat.VolumeMixer.Tester\EonaCat.VolumeMixer.Tester.csproj", "{9156F465-62F7-BA83-40E6-F4FD7F0AA6A2}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{11B9181D-7186-4D81-A5D3-4804E9A61BA6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{11B9181D-7186-4D81-A5D3-4804E9A61BA6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{11B9181D-7186-4D81-A5D3-4804E9A61BA6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{11B9181D-7186-4D81-A5D3-4804E9A61BA6}.Release|Any CPU.Build.0 = Release|Any CPU
{9156F465-62F7-BA83-40E6-F4FD7F0AA6A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9156F465-62F7-BA83-40E6-F4FD7F0AA6A2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9156F465-62F7-BA83-40E6-F4FD7F0AA6A2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9156F465-62F7-BA83-40E6-F4FD7F0AA6A2}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {B839F1D9-578B-4D9F-A8E5-43763F9B1C57}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,52 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<LangVersion>Latest</LangVersion>
<TargetFrameworks>
net47;
netstandard2.0;
netstandard2.1;
net6.0;
net8.0;
</TargetFrameworks>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<PackageId>EonaCat.VolumeMixer</PackageId>
<Authors>EonaCat (Jeroen Saey)</Authors>
<Company>EonaCat (Jeroen Saey)</Company>
<Product>EonaCat.VolumeMixer</Product>
<Copyright>EonaCat (Jeroen Saey)</Copyright>
<PackageProjectUrl>https://www.nuget.org/packages/EonaCat.VolumeMixer/</PackageProjectUrl>
<PackageTags>EonaCat, Audio, Volume, Mixer .NET Standard, Jeroen, Saey</PackageTags>
<PackageReleaseNotes></PackageReleaseNotes>
<Description>EonaCat VolumeMixer</Description>
<Version>1.0.0</Version>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
<FileVersion>1.0.0.0</FileVersion>
<PackageIcon>icon.png</PackageIcon>
</PropertyGroup>
<PropertyGroup>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<PackageReadmeFile>README.md</PackageReadmeFile>
<SignAssembly>False</SignAssembly>
<Title>EonaCat.VolumeMixer</Title>
<PackageRequireLicenseAcceptance>True</PackageRequireLicenseAcceptance>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
</PropertyGroup>
<ItemGroup>
<None Include="..\icon.png">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
<None Include="..\LICENSE">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
<None Include="..\README.md">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,42 @@
using System;
using System.Runtime.InteropServices;
namespace EonaCat.VolumeMixer.Helpers
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
internal static class ComHelper
{
public static T GetInterface<T>(IntPtr ptr) where T : class
{
if (ptr == IntPtr.Zero)
{
return null;
}
try
{
return Marshal.GetObjectForIUnknown(ptr) as T;
}
catch
{
return null;
}
finally
{
if (ptr != IntPtr.Zero)
{
Marshal.Release(ptr);
}
}
}
public static void ReleaseComObject(object obj)
{
if (obj != null && Marshal.IsComObject(obj))
{
Marshal.ReleaseComObject(obj);
}
}
}
}

View File

@ -0,0 +1,32 @@
using System;
using System.Runtime.InteropServices;
namespace EonaCat.VolumeMixer.Interfaces
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
[ComImport]
[Guid("5CDF2C82-841E-4546-9722-0CF74078229A")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IAudioEndpointVolume
{
int RegisterControlChangeNotify(IntPtr pNotify);
int UnregisterControlChangeNotify(IntPtr pNotify);
int GetChannelCount(out uint pnChannelCount);
int SetMasterVolumeLevel(float fLevelDB, ref Guid pguidEventContext);
int SetMasterVolumeLevelScalar(float fLevel, ref Guid pguidEventContext);
int GetMasterVolumeLevel(out float pfLevelDB);
int GetMasterVolumeLevelScalar(out float pfLevel);
int SetChannelVolumeLevel(uint nChannel, float fLevelDB, ref Guid pguidEventContext);
int SetChannelVolumeLevelScalar(uint nChannel, float fLevel, ref Guid pguidEventContext);
int GetChannelVolumeLevel(uint nChannel, out float pfLevelDB);
int GetChannelVolumeLevelScalar(uint nChannel, out float pfLevel);
int SetMute([MarshalAs(UnmanagedType.Bool)] bool bMute, ref Guid pguidEventContext);
int GetMute([MarshalAs(UnmanagedType.Bool)] out bool pbMute);
int GetVolumeStepInfo(out uint pnStep, out uint pnStepCount);
int StepUp(ref Guid pguidEventContext);
int StepDown(ref Guid pguidEventContext);
int QueryHardwareSupport(out uint pdwHardwareSupportMask);
int GetVolumeRange(out float pflVolumeMindB, out float pflVolumeMaxdB, out float pflVolumeIncrementdB);
}
}

View File

@ -0,0 +1,24 @@
using EonaCat.VolumeMixer.Models;
using System;
using System.Runtime.InteropServices;
namespace EonaCat.VolumeMixer.Interfaces
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
[ComImport]
[Guid("F4B1A599-7266-4319-A8CA-E70ACB11E8CD")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IAudioSessionControl
{
int GetState(out AudioSessionState pRetVal);
int GetDisplayName([MarshalAs(UnmanagedType.LPWStr)] out string pRetVal);
int SetDisplayName([MarshalAs(UnmanagedType.LPWStr)] string Value, ref Guid EventContext);
int GetIconPath([MarshalAs(UnmanagedType.LPWStr)] out string pRetVal);
int SetIconPath([MarshalAs(UnmanagedType.LPWStr)] string Value, ref Guid EventContext);
int GetGroupingParam(out Guid pRetVal);
int SetGroupingParam(ref Guid Override, ref Guid EventContext);
int RegisterAudioSessionNotification(IntPtr NewNotifications);
int UnregisterAudioSessionNotification(IntPtr NewNotifications);
}
}

View File

@ -0,0 +1,31 @@
using EonaCat.VolumeMixer.Models;
using System;
using System.Runtime.InteropServices;
namespace EonaCat.VolumeMixer.Interfaces
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
[ComImport]
[Guid("BFB7FF88-7239-4FC9-8FA2-07C950BE9C6D")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IAudioSessionControlExtended : IAudioSessionControl
{
new int GetState(out AudioSessionState pRetVal);
new int GetDisplayName([MarshalAs(UnmanagedType.LPWStr)] out string pRetVal);
new int SetDisplayName([MarshalAs(UnmanagedType.LPWStr)] string Value, ref Guid EventContext);
new int GetIconPath([MarshalAs(UnmanagedType.LPWStr)] out string pRetVal);
new int SetIconPath([MarshalAs(UnmanagedType.LPWStr)] string Value, ref Guid EventContext);
new int GetGroupingParam(out Guid pRetVal);
new int SetGroupingParam(ref Guid Override, ref Guid EventContext);
new int RegisterAudioSessionNotification(IntPtr NewNotifications);
new int UnregisterAudioSessionNotification(IntPtr NewNotifications);
// IAudioSessionControl2 specific methods
int GetSessionIdentifier([MarshalAs(UnmanagedType.LPWStr)] out string pRetVal);
int GetSessionInstanceIdentifier([MarshalAs(UnmanagedType.LPWStr)] out string pRetVal);
int GetProcessId(out uint pRetVal);
int IsSystemSoundsSession();
int SetDuckingPreference([MarshalAs(UnmanagedType.Bool)] bool optOut);
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Runtime.InteropServices;
namespace EonaCat.VolumeMixer.Interfaces
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
[ComImport]
[Guid("E2F5BB11-0570-40CA-ACDD-3AA01277DEE8")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IAudioSessionEnumerator
{
int GetCount(out int SessionCount);
int GetSession(int SessionNumber, out IAudioSessionControlExtended Session);
}
}

View File

@ -0,0 +1,21 @@
using System;
using System.Runtime.InteropServices;
namespace EonaCat.VolumeMixer.Interfaces
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
[ComImport]
[Guid("77AA99A0-1BD6-484F-8BC7-2C654C9A9B6F")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IAudioSessionManager
{
int GetAudioSessionControl(ref Guid AudioSessionGuid, uint StreamFlags, out IntPtr SessionControl);
int GetAudioVolume(ref Guid AudioSessionGuid, uint StreamFlags, out IntPtr AudioVolume);
int GetSessionEnumerator(out IAudioSessionEnumerator SessionEnum);
int RegisterSessionNotification(IntPtr SessionNotification);
int UnregisterSessionNotification(IntPtr SessionNotification);
int RegisterDuckNotification([MarshalAs(UnmanagedType.LPWStr)] string sessionID, IntPtr duckNotification);
int UnregisterDuckNotification(IntPtr duckNotification);
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Runtime.InteropServices;
namespace EonaCat.VolumeMixer.Interfaces
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
[ComImport]
[Guid("87CE5498-68D6-44E5-9215-6DA47EF883D8")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IAudioVolume
{
int SetMasterVolume(float fLevel, ref Guid EventContext);
int GetMasterVolume(out float pfLevel);
int SetMute([MarshalAs(UnmanagedType.Bool)] bool bMute, ref Guid EventContext);
int GetMute([MarshalAs(UnmanagedType.Bool)] out bool pbMute);
}
}

View File

@ -0,0 +1,19 @@
using EonaCat.VolumeMixer.Models;
using System;
using System.Runtime.InteropServices;
namespace EonaCat.VolumeMixer.Interfaces
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
[ComImport]
[Guid("D666063F-1587-4E43-81F1-B948E807363F")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IMultiMediaDevice
{
int Activate(ref Guid iid, uint dwClsCtx, IntPtr pActivationParams, out IntPtr ppInterface);
int OpenPropertyStore(uint stgmAccess, out IPropertyStore ppProperties);
int GetId([MarshalAs(UnmanagedType.LPWStr)] out string ppstrId);
int GetState(out DeviceState pdwState);
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Runtime.InteropServices;
namespace EonaCat.VolumeMixer.Interfaces
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
[ComImport]
[Guid("0BD7A1BE-7A1A-44DB-8397-CC5392387B5E")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IMultiMediaDeviceCollection
{
int GetCount(out uint pcDevices);
int Item(uint nDevice, out IMultiMediaDevice ppDevice);
}
}

View File

@ -0,0 +1,20 @@
using EonaCat.VolumeMixer.Models;
using System;
using System.Runtime.InteropServices;
namespace EonaCat.VolumeMixer.Interfaces
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
[ComImport]
[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IMultiMediaDeviceEnumerator
{
int EnumAudioEndpoints(DataFlow dataFlow, DeviceState dwStateMask, out IMultiMediaDeviceCollection ppDevices);
int GetDefaultAudioEndpoint(DataFlow dataFlow, Role role, out IMultiMediaDevice ppEndpoint);
int GetDevice([MarshalAs(UnmanagedType.LPWStr)] string pwstrId, out IMultiMediaDevice ppDevice);
int RegisterEndpointNotificationCallback(IntPtr pClient);
int UnregisterEndpointNotificationCallback(IntPtr pClient);
}
}

View File

@ -0,0 +1,20 @@
using EonaCat.VolumeMixer.Models;
using System;
using System.Runtime.InteropServices;
namespace EonaCat.VolumeMixer.Interfaces
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
[ComImport]
[Guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IPropertyStore
{
int GetCount(out uint cProps);
int GetAt(uint iProp, out PropertyKey pkey);
int GetValue(ref PropertyKey key, out PropVariant pv);
int SetValue(ref PropertyKey key, ref PropVariant propvar);
int Commit();
}
}

View File

@ -0,0 +1,146 @@
using EonaCat.VolumeMixer.Models;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace EonaCat.VolumeMixer.Managers
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public class MicrophoneManager : IDisposable
{
private readonly VolumeMixerManager _volumeMixer;
private readonly object _syncLock = new();
public MicrophoneManager()
{
_volumeMixer = new VolumeMixerManager();
}
public async Task<List<AudioDevice>> GetMicrophonesAsync()
{
return await _volumeMixer.GetAudioDevicesAsync(DataFlow.Input);
}
public async Task<AudioDevice> GetDefaultMicrophoneAsync()
{
return await _volumeMixer.GetDefaultAudioDeviceAsync(DataFlow.Input);
}
public async Task<bool> SetMicrophoneVolumeAsync(float volume)
{
if (volume < 0f || volume > 1f)
{
return false;
}
AudioDevice defaultMic = await GetDefaultMicrophoneAsync();
if (defaultMic == null)
{
return false;
}
try
{
return await defaultMic.SetMasterVolumeAsync(volume);
}
finally
{
defaultMic.Dispose();
}
}
public async Task<float> GetMicrophoneVolumeAsync()
{
AudioDevice defaultMic = await GetDefaultMicrophoneAsync();
if (defaultMic == null)
{
return 0f;
}
try
{
return await defaultMic.GetMasterVolumeAsync();
}
finally
{
defaultMic.Dispose();
}
}
public async Task<bool> SetMicrophoneMuteAsync(bool mute)
{
AudioDevice defaultMic = await GetDefaultMicrophoneAsync();
if (defaultMic == null)
{
return false;
}
try
{
return await defaultMic.SetMasterMuteAsync(mute);
}
finally
{
defaultMic.Dispose();
}
}
public async Task<bool> GetMicrophoneMuteAsync()
{
AudioDevice defaultMic = await GetDefaultMicrophoneAsync();
if (defaultMic == null)
{
return false;
}
try
{
return await defaultMic.GetMasterMuteAsync();
}
finally
{
defaultMic.Dispose();
}
}
public async Task<bool> SetMicrophoneVolumeByNameAsync(string microphoneName, float volume)
{
if (string.IsNullOrWhiteSpace(microphoneName) || volume < 0f || volume > 1f)
{
return false;
}
List<AudioDevice> microphones = await GetMicrophonesAsync();
foreach (var mic in microphones)
{
try
{
if (mic.Name.IndexOf(microphoneName, StringComparison.OrdinalIgnoreCase) >= 0)
{
return await mic.SetMasterVolumeAsync(volume);
}
}
finally
{
mic.Dispose();
}
}
return false;
}
public void Dispose()
{
lock (_syncLock)
{
_volumeMixer?.Dispose();
}
}
}
}

View File

@ -0,0 +1,297 @@
using EonaCat.VolumeMixer.Helpers;
using EonaCat.VolumeMixer.Interfaces;
using EonaCat.VolumeMixer.Models;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace EonaCat.VolumeMixer.Managers
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public class VolumeMixerManager : IDisposable
{
private readonly IMultiMediaDeviceEnumerator _deviceEnumerator;
private bool _isDisposed = false;
private readonly object _syncLock = new();
private static readonly PropertyKey PKEY_Device_FriendlyName = new PropertyKey(new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), 14);
public VolumeMixerManager()
{
try
{
_deviceEnumerator = (IMultiMediaDeviceEnumerator)new MMDeviceEnumerator();
}
catch (Exception ex)
{
throw new InvalidOperationException("Failed to initialize audio device enumerator. Make sure you're running on Windows Vista or later.", ex);
}
}
public async Task<List<AudioDevice>> GetAudioDevicesAsync(DataFlow dataFlow = DataFlow.Output)
{
return await Task.Run(() =>
{
var devices = new List<AudioDevice>();
if (_deviceEnumerator == null)
{
return devices;
}
lock (_syncLock)
{
try
{
var result = _deviceEnumerator.EnumAudioEndpoints(dataFlow, DeviceState.Active, out var deviceCollection);
if (result != 0 || deviceCollection == null)
{
return devices;
}
result = deviceCollection.GetCount(out var count);
if (result != 0)
{
return devices;
}
string defaultId = "";
try
{
result = _deviceEnumerator.GetDefaultAudioEndpoint(dataFlow, Role.Multimedia, out var defaultDevice);
if (result == 0 && defaultDevice != null)
{
defaultDevice.GetId(out defaultId);
ComHelper.ReleaseComObject(defaultDevice);
}
}
catch
{
defaultId = "";
}
for (uint i = 0; i < count; i++)
{
try
{
result = deviceCollection.Item(i, out var device);
if (result == 0 && device != null)
{
result = device.GetId(out var id);
if (result == 0 && !string.IsNullOrEmpty(id))
{
var name = GetDeviceName(device);
bool isDefault = id == defaultId;
devices.Add(new AudioDevice(device, id, name, isDefault, dataFlow));
}
else
{
ComHelper.ReleaseComObject(device);
}
}
}
catch
{
// Skip individual device on error
}
}
ComHelper.ReleaseComObject(deviceCollection);
}
catch
{
// Ignore all and return partial/empty result
}
}
return devices;
});
}
public async Task<AudioDevice> GetDefaultAudioDeviceAsync(DataFlow dataFlow = DataFlow.Output)
{
return await Task.Run(() =>
{
if (_deviceEnumerator == null)
{
return null;
}
lock (_syncLock)
{
try
{
var result = _deviceEnumerator.GetDefaultAudioEndpoint(dataFlow, Role.Multimedia, out var device);
if (result == 0 && device != null)
{
result = device.GetId(out var id);
if (result == 0 && !string.IsNullOrEmpty(id))
{
var name = GetDeviceName(device);
return new AudioDevice(device, id, name, true, dataFlow);
}
ComHelper.ReleaseComObject(device);
}
}
catch
{
// Ignore and return null
}
return null;
}
});
}
private string GetDeviceName(IMultiMediaDevice device)
{
try
{
var result = device.OpenPropertyStore(0, out var propertyStore);
if (result == 0 && propertyStore != null)
{
var propertyKey = PKEY_Device_FriendlyName;
result = propertyStore.GetValue(ref propertyKey, out var propVariant);
if (result == 0 && propVariant.data != IntPtr.Zero)
{
string name = Marshal.PtrToStringUni(propVariant.data);
ComHelper.ReleaseComObject(propertyStore);
return !string.IsNullOrEmpty(name) ? name : "Unknown Device";
}
ComHelper.ReleaseComObject(propertyStore);
}
}
catch
{
// Ignore and fall through
}
return "Unknown Device";
}
public async Task<bool> SetSystemVolumeAsync(float volume)
{
if (volume < 0f || volume > 1f)
{
return false;
}
AudioDevice defaultDevice = await GetDefaultAudioDeviceAsync();
if (defaultDevice == null)
{
return false;
}
try
{
return await defaultDevice.SetMasterVolumeAsync(volume);
}
finally
{
defaultDevice.Dispose();
}
}
public async Task<float> GetSystemVolumeAsync()
{
AudioDevice defaultDevice = await GetDefaultAudioDeviceAsync();
if (defaultDevice == null)
{
return 0f;
}
try
{
return await defaultDevice.GetMasterVolumeAsync();
}
finally
{
defaultDevice.Dispose();
}
}
public async Task<bool> SetSystemMuteAsync(bool mute)
{
AudioDevice defaultDevice = await GetDefaultAudioDeviceAsync();
if (defaultDevice == null)
{
return false;
}
try
{
return await defaultDevice.SetMasterMuteAsync(mute);
}
finally
{
defaultDevice.Dispose();
}
}
public async Task<bool> GetSystemMuteAsync()
{
AudioDevice defaultDevice = await GetDefaultAudioDeviceAsync();
if (defaultDevice == null)
{
return false;
}
try
{
return await defaultDevice.GetMasterMuteAsync();
}
finally
{
defaultDevice.Dispose();
}
}
public async Task<List<AudioSession>> GetAllActiveSessionsAsync()
{
return await Task.Run(async () =>
{
var allSessions = new List<AudioSession>();
List<AudioDevice> devices = await GetAudioDevicesAsync();
foreach (var device in devices)
{
try
{
allSessions.AddRange(await device.GetAudioSessionsAsync());
}
catch
{
// Skip device on error
}
finally
{
device.Dispose();
}
}
return allSessions;
});
}
public void Dispose()
{
lock (_syncLock)
{
if (!_isDisposed)
{
ComHelper.ReleaseComObject(_deviceEnumerator);
_isDisposed = true;
}
}
}
}
}

View File

@ -0,0 +1,304 @@
using EonaCat.VolumeMixer.Helpers;
using EonaCat.VolumeMixer.Interfaces;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace EonaCat.VolumeMixer.Models
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public class AudioDevice : IDisposable
{
private readonly IMultiMediaDevice _device;
private IAudioEndpointVolume _endpointVolume;
private IAudioSessionManager _sessionManager;
private bool _isDisposed = false;
private readonly object _syncLock = new object();
public string Id { get; private set; }
public string Name { get; private set; }
public bool IsDefault { get; private set; }
public DataFlow DataFlow { get; private set; }
internal AudioDevice(IMultiMediaDevice device, string id, string name, bool isDefault, DataFlow dataFlow)
{
_device = device;
Id = id;
Name = name;
IsDefault = isDefault;
DataFlow = dataFlow;
InitializeEndpointVolume();
InitializeSessionManager();
}
private void InitializeEndpointVolume()
{
try
{
var audioEndpointGuid = typeof(IAudioEndpointVolume).GUID;
var result = _device.Activate(ref audioEndpointGuid, 0, IntPtr.Zero, out var ptr);
if (result == 0 && ptr != IntPtr.Zero)
{
_endpointVolume = ComHelper.GetInterface<IAudioEndpointVolume>(ptr);
}
}
catch
{
_endpointVolume = null;
}
}
private void InitializeSessionManager()
{
try
{
var audioSessionGuid = typeof(IAudioSessionManager).GUID;
var result = _device.Activate(ref audioSessionGuid, 0, IntPtr.Zero, out var ptr);
if (result == 0 && ptr != IntPtr.Zero)
{
_sessionManager = ComHelper.GetInterface<IAudioSessionManager>(ptr);
}
}
catch
{
_sessionManager = null;
}
}
public async Task<float> GetMasterVolumeAsync()
{
return await Task.Run(() =>
{
lock (_syncLock)
{
if (_isDisposed || _endpointVolume == null)
{
return 0f;
}
try
{
var hr = _endpointVolume.GetMasterVolumeLevelScalar(out var volume);
return hr == 0 ? volume : 0f;
}
catch
{
return 0f;
}
}
});
}
public async Task<bool> SetMasterVolumeAsync(float volume, int maxRetries = 5, int delayMs = 20)
{
for (int attempt = 0; attempt <= maxRetries; attempt++)
{
lock (_syncLock)
{
if (_isDisposed || _endpointVolume == null || volume < 0f || volume > 1f)
{
return false;
}
try
{
var guid = Guid.Empty;
var result = _endpointVolume.SetMasterVolumeLevelScalar(volume, ref guid);
if (result != 0)
{
// Failed to set, will retry
continue;
}
}
catch
{
// Retry on exception
continue;
}
}
await Task.Delay(delayMs);
var currentVolume = await GetMasterVolumeAsync();
if (Math.Abs(currentVolume - volume) < 0.01f)
{
return true;
}
await Task.Delay(delayMs);
}
return false;
}
public async Task<bool> GetMasterMuteAsync()
{
return await Task.Run(() =>
{
lock (_syncLock)
{
if (_isDisposed || _endpointVolume == null)
{
return false;
}
try
{
var result = _endpointVolume.GetMute(out var mute);
return result == 0 ? mute : false;
}
catch
{
return false;
}
}
});
}
public async Task<bool> SetMasterMuteAsync(bool mute)
{
IAudioEndpointVolume endpointVolumeCopy;
lock (_syncLock)
{
if (_isDisposed || _endpointVolume == null)
{
return false;
}
endpointVolumeCopy = _endpointVolume;
}
try
{
var guid = Guid.Empty;
return await Task.Run(() => endpointVolumeCopy.SetMute(mute, ref guid) == 0);
}
catch
{
return false;
}
}
public async Task<List<AudioSession>> GetAudioSessionsAsync()
{
return await Task.Run(() =>
{
lock (_syncLock)
{
var sessions = new List<AudioSession>();
if (_isDisposed || _sessionManager == null)
{
return sessions;
}
try
{
var result = _sessionManager.GetSessionEnumerator(out var sessionEnum);
if (result != 0 || sessionEnum == null)
{
return sessions;
}
result = sessionEnum.GetCount(out var count);
if (result != 0)
{
return sessions;
}
for (int i = 0; i < count; i++)
{
try
{
result = sessionEnum.GetSession(i, out var sessionControl);
if (result == 0 && sessionControl != null)
{
sessions.Add(new AudioSession(sessionControl, _sessionManager));
}
}
catch
{
// Skip on error
}
}
}
catch
{
// Return empty
}
return sessions;
}
});
}
public async Task<bool> StepUpAsync(int delayMs = 20)
{
bool success = false;
lock (_syncLock)
{
if (_isDisposed || _endpointVolume == null)
{
return false;
}
try
{
var guid = Guid.Empty;
var result = _endpointVolume.StepUp(ref guid);
success = result == 0;
}
catch
{
success = false;
}
}
await Task.Delay(delayMs);
return success;
}
public async Task<bool> StepDownAsync(int delayMs = 20)
{
bool success = false;
lock (_syncLock)
{
if (_isDisposed || _endpointVolume == null)
{
return false;
}
try
{
var guid = Guid.Empty;
var result = _endpointVolume.StepDown(ref guid);
success = result == 0;
}
catch
{
success = false;
}
}
await Task.Delay(delayMs);
return success;
}
public void Dispose()
{
lock (_syncLock)
{
if (_isDisposed)
{
return;
}
ComHelper.ReleaseComObject(_endpointVolume);
ComHelper.ReleaseComObject(_sessionManager);
ComHelper.ReleaseComObject(_device);
_isDisposed = true;
}
}
}
}

View File

@ -0,0 +1,239 @@
using EonaCat.VolumeMixer.Helpers;
using EonaCat.VolumeMixer.Interfaces;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
namespace EonaCat.VolumeMixer.Models
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public class AudioSession : IDisposable
{
private readonly IAudioSessionControlExtended _sessionControl;
private IAudioVolume _audioVolume;
private bool _isDisposed = false;
private readonly object _syncLock = new object();
public string DisplayName { get; private set; }
public string IconPath { get; private set; }
public uint ProcessId { get; private set; }
public AudioSessionState State { get; private set; }
internal AudioSession(IAudioSessionControlExtended sessionControl, IAudioSessionManager sessionManager)
{
_sessionControl = sessionControl;
LoadSessionInfo();
InitializeVolume(sessionManager);
}
private void InitializeVolume(IAudioSessionManager sessionManager)
{
lock (_syncLock)
{
try
{
var result = _sessionControl.GetGroupingParam(out var guid);
if (result == 0)
{
result = sessionManager.GetAudioVolume(ref guid, 0, out var ptr);
if (result == 0 && ptr != IntPtr.Zero)
{
_audioVolume = ComHelper.GetInterface<IAudioVolume>(ptr);
}
}
}
catch
{
_audioVolume = null;
}
}
}
private void LoadSessionInfo()
{
lock (_syncLock)
{
try
{
var result = _sessionControl.GetDisplayName(out var displayName);
DisplayName = result == 0 && !string.IsNullOrEmpty(displayName) ? displayName : string.Empty;
result = _sessionControl.GetIconPath(out var iconPath);
IconPath = result == 0 ? iconPath ?? "" : "";
result = _sessionControl.GetProcessId(out var processId);
ProcessId = result == 0 ? processId : 0;
result = _sessionControl.GetState(out var state);
State = result == 0 ? state : AudioSessionState.AudioSessionStateInactive;
}
catch
{
DisplayName = string.Empty;
IconPath = string.Empty;
ProcessId = 0;
State = AudioSessionState.AudioSessionStateInactive;
}
}
}
public async Task<float> GetVolumeAsync()
{
return await Task.Run(() =>
{
lock (_syncLock)
{
if (_isDisposed || _audioVolume == null)
{
return 0f;
}
try
{
var result = _audioVolume.GetMasterVolume(out var volume);
return result == 0 ? volume : 0f;
}
catch
{
return 0f;
}
}
});
}
public async Task<bool> SetVolumeAsync(float volume, int maxRetries = 2, int delayMs = 20)
{
if (volume < 0f || volume > 1f)
{
return false;
}
IAudioVolume audioVolCopy;
lock (_syncLock)
{
if (_isDisposed || _audioVolume == null)
{
return false;
}
audioVolCopy = _audioVolume;
}
var guid = Guid.Empty;
for (int attempt = 0; attempt <= maxRetries; attempt++)
{
try
{
var hr = audioVolCopy.SetMasterVolume(volume, ref guid);
if (hr == 0)
{
await Task.Delay(delayMs);
var currentVolume = await GetVolumeAsync();
if (Math.Abs(currentVolume - volume) < 0.01f)
{
return true;
}
}
}
catch
{
// Retry
}
await Task.Delay(delayMs);
}
return false;
}
public async Task<bool> GetMuteAsync()
{
return await Task.Run(() =>
{
lock (_syncLock)
{
if (_isDisposed || _audioVolume == null)
{
return false;
}
try
{
var result = _audioVolume.GetMute(out var mute);
return result == 0 ? mute : false;
}
catch
{
return false;
}
}
});
}
public async Task<bool> SetMuteAsync(bool mute)
{
IAudioVolume audioVolCopy;
lock (_syncLock)
{
if (_isDisposed || _audioVolume == null)
{
return false;
}
audioVolCopy = _audioVolume;
}
try
{
var guid = Guid.Empty;
return await Task.Run(() => audioVolCopy.SetMute(mute, ref guid) == 0);
}
catch
{
return false;
}
}
public async Task<string> GetProcessNameAsync()
{
return await Task.Run(() =>
{
lock (_syncLock)
{
if (ProcessId == 0)
{
return "Unknown";
}
try
{
var process = Process.GetProcessById((int)ProcessId);
return process.ProcessName;
}
catch
{
return "Unknown";
}
}
});
}
public void Dispose()
{
lock (_syncLock)
{
if (_isDisposed)
{
return;
}
ComHelper.ReleaseComObject(_audioVolume);
ComHelper.ReleaseComObject(_sessionControl);
_isDisposed = true;
}
}
}
}

View File

@ -0,0 +1,11 @@
namespace EonaCat.VolumeMixer.Models
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public enum AudioSessionState
{
AudioSessionStateInactive = 0,
AudioSessionStateActive = 1,
AudioSessionStateExpired = 2
}
}

View File

@ -0,0 +1,11 @@
namespace EonaCat.VolumeMixer.Models
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public enum DataFlow
{
Output,
Input,
All
}
}

View File

@ -0,0 +1,13 @@
namespace EonaCat.VolumeMixer.Models
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
internal enum DeviceState : uint
{
Active = 0x00000001,
Disabled = 0x00000002,
NotPresent = 0x00000004,
Unplugged = 0x00000008,
All = 0x0000000F
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Runtime.InteropServices;
namespace EonaCat.VolumeMixer.Models
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
[ComImport]
[Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")]
internal class MMDeviceEnumerator
{
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Runtime.InteropServices;
namespace EonaCat.VolumeMixer.Models
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
[StructLayout(LayoutKind.Sequential)]
internal struct PropVariant
{
public ushort vt;
public ushort wReserved1;
public ushort wReserved2;
public ushort wReserved3;
public IntPtr data;
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Runtime.InteropServices;
namespace EonaCat.VolumeMixer.Models
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
[StructLayout(LayoutKind.Sequential)]
internal struct PropertyKey
{
public Guid fmtid;
public uint pid;
public PropertyKey(Guid fmtid, uint pid)
{
this.fmtid = fmtid;
this.pid = pid;
}
}
}

View File

@ -0,0 +1,11 @@
namespace EonaCat.VolumeMixer.Models
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
internal enum Role
{
Console,
Multimedia,
Communications
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

213
LICENSE
View File

@ -1,73 +1,204 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
https://EonaCat.com/license/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
OF SOFTWARE BY EONACAT (JEROEN SAEY)
1. Definitions.
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2025 EonaCat
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

272
README.md
View File

@ -1,3 +1,273 @@
# EonaCat.VolumeMixer
EonaCat.VolumeMixer Library
------------
The EonaCat.VolumeMixer library provides an interface to interact with individual audio sessions on Windows.
It allows you to retrieve and modify the volume and mute state of a session, get session metadata, and access information about the associated process.
This class uses Windows Core Audio APIs via COM interop to manage audio sessions, making it suitable for applications that need fine-grained control over audio streams per process or session.
## Features
- Get and set audio session volume asynchronously
- Get and set mute state asynchronously
- Retrieve session metadata such as display name, icon path, process ID, and state
- Get the name of the process owning the session
- Thread-safe operations with internal synchronization
- Proper cleanup of COM resources through implementation of IDisposable
## Note
Volume and mute setters are asynchronous and include retry logic for reliability.
Volume values must be between 0.0 (silent) and 1.0 (max volume).
Getting process name returns "Unknown" if the process cannot be found.
Thread-safe for concurrent use.
Requires Windows Vista or later with Core Audio APIs.
## Dependencies
Must be run with permissions that allow access to audio session interfaces.
### Accessing session state:
```csharp
using EonaCat.VolumeMixer;
IAudioSessionControlExtended sessionControl = /* obtained from enumerator */;
IAudioSessionManager sessionManager = /* obtained from audio device */;
var audioSession = new AudioSession(sessionControl, sessionManager);
string displayName = audioSession.DisplayName;
string iconPath = audioSession.IconPath;
uint processId = audioSession.ProcessId;
AudioSessionState state = audioSession.State;
```
### Obtaining current volume and mute state:
```csharp
// Get current volume (0.0 to 1.0)
float volume = audioSession.GetVolume();
// Set volume asynchronously
bool success = await audioSession.SetVolumeAsync(0.75f);
if (success)
{
Console.WriteLine("Volume set successfully");
}
else
{
Console.WriteLine("Failed to set volume");
}
```
### Mute control:
```csharp
// Get mute status
bool isMuted = audioSession.GetMute();
// Set mute asynchronously
bool muteSuccess = await audioSession.SetMuteAsync(true);
if (muteSuccess)
{
Console.WriteLine("Muted successfully");
}
else
{
Console.WriteLine("Failed to mute");
}
```
### Process Information:
```csharp
string processName = audioSession.GetProcessName();
Console.WriteLine($"Audio session process: {processName}");
```
### Playback management example:
```csharp
using EonaCat.VolumeMixer.Managers;
using EonaCat.VolumeMixer.Models;
using System;
using System.Threading.Tasks;
class Program
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
[STAThread]
static async Task Main()
{
// Playback management example
using (var volumeMixer = new VolumeMixerManager())
{
try
{
// Get all audio PLAYBACK devices
var devices = await volumeMixer.GetAudioDevicesAsync(DataFlow.Output);
Console.WriteLine($"Found {devices.Count} playback devices:");
foreach (var device in devices)
{
Console.WriteLine($"- {device.Name} (Default: {device.IsDefault})");
Console.WriteLine($" Volume: {await device.GetMasterVolumeAsync():P0}");
Console.WriteLine($" Muted: {await device.GetMasterMuteAsync()}");
device.Dispose();
}
// Default playback device
using (var defaultDevice = await volumeMixer.GetDefaultAudioDeviceAsync(DataFlow.Output))
{
if (defaultDevice != null)
{
Console.WriteLine($"\nDefault playback device: {defaultDevice.Name}");
// Get all audio sessions
var sessions = await defaultDevice.GetAudioSessionsAsync();
Console.WriteLine($"Active sessions: {sessions.Count}");
foreach (var session in sessions)
{
Console.WriteLine($"- {session.DisplayName} ({await session.GetProcessNameAsync()})");
Console.WriteLine($" Volume: {await session.GetVolumeAsync():P0}");
Console.WriteLine($" Muted: {await session.GetMuteAsync()}");
session.Dispose();
}
}
// Example Set volume of default device
if (defaultDevice != null)
{
// Unmute the device if it is muted
if (await defaultDevice.GetMasterMuteAsync())
{
Console.WriteLine("Unmuting default playback device...");
await defaultDevice.SetMasterMuteAsync(false);
}
Console.WriteLine($"\nSetting default playback device volume to 1%");
bool success = await defaultDevice.SetMasterVolumeAsync(0.1f);
// Log the current volume
Console.WriteLine($"Current volume: {await defaultDevice.GetMasterVolumeAsync():P0}");
for (int i = 0; i < 50; i++)
{
if (await defaultDevice.GetMasterVolumeAsync() >= 1f)
{
break;
}
// Increment volume by 2% each step
success = await defaultDevice.StepUpAsync();
Console.WriteLine($"Current step volume: {await defaultDevice.GetMasterVolumeAsync():P0}");
}
if (success)
{
Console.WriteLine("Volume increased by 95% successfully.");
}
else
{
Console.WriteLine("Failed to increase volume.");
}
// Toggle mute
// bool currentMute = await defaultDevice.GetMasterMuteAsync();
// success = await defaultDevice.SetMasterMuteAsync(!currentMute);
// Console.WriteLine($"Mute toggled: {success}");
}
else
{
Console.WriteLine("No default playback device found");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
}
```
### Microphone management example:
```csharp
using EonaCat.VolumeMixer.Managers;
using EonaCat.VolumeMixer.Models;
using System;
using System.Threading.Tasks;
class Program
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
[STAThread]
static async Task Main()
{
// Microphone management example
using (var micManager = new MicrophoneManager())
{
try
{
// Get all microphones
var microphones = await micManager.GetMicrophonesAsync();
Console.WriteLine($"Found {microphones.Count} microphones:");
foreach (var mic in microphones)
{
Console.WriteLine($"- {mic.Name} (Default: {mic.IsDefault})");
Console.WriteLine($" Volume: {await mic.GetMasterVolumeAsync():P0}");
Console.WriteLine($" Muted: {await mic.GetMasterMuteAsync()}");
mic.Dispose();
}
// Default microphone
using (var defaultMic = await micManager.GetDefaultMicrophoneAsync())
{
Console.WriteLine($"\nSetting default microphone volume to 1%");
bool success = await defaultMic.SetMasterVolumeAsync(0.1f);
// Log the current volume
Console.WriteLine($"Current volume: {await defaultMic.GetMasterVolumeAsync():P0}");
for (int i = 0; i < 50; i++)
{
if (await defaultMic.GetMasterVolumeAsync() >= 1f)
{
break;
}
// Increment volume by 2% each step
success = await defaultMic.StepUpAsync();
Console.WriteLine($"Current step volume: {await defaultMic.GetMasterVolumeAsync():P0}");
}
if (success)
{
Console.WriteLine("Volume increased by 95% successfully.");
}
else
{
Console.WriteLine("Failed to increase volume.");
}
}
Console.WriteLine($"Default mic volume: {await micManager.GetMicrophoneVolumeAsync():P0}");
Console.WriteLine($"Default mic muted: {await micManager.GetMicrophoneMuteAsync()}");
// Set microphone volume to 60%
bool result = await micManager.SetMicrophoneVolumeAsync(0.6f);
Console.WriteLine($"Set microphone volume to 60%: {result}");
// Set specific microphone by name
result = await micManager.SetMicrophoneVolumeByNameAsync("USB", 0.7f);
Console.WriteLine($"Set USB microphone volume to 70%: {result}");
}
catch (Exception exception)
{
Console.WriteLine($"Error: {exception.Message}");
}
}
}
}
```

BIN
icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB