Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 20 additions & 21 deletions SpotifyAPI/Local/VolumeMixerControl.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,17 @@
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;

namespace SpotifyAPI.Local
{
internal class VolumeMixerControl
internal static class VolumeMixerControl
{
private const String SpotifyProcessName = "spotify";

internal static float GetSpotifyVolume()
{
Process[] p = Process.GetProcessesByName(SpotifyProcessName);
if (p.Length == 0)
throw new Exception("Spotify process is not running or was not found!");

int pid = p[0].Id;
int pid = GetSpotifyPid();

ISimpleAudioVolume volume = GetVolumeObject(pid);
if (volume == null)
Expand All @@ -30,11 +27,7 @@ internal static float GetSpotifyVolume()

internal static bool IsSpotifyMuted()
{
Process[] p = Process.GetProcessesByName(SpotifyProcessName);
if (p.Length == 0)
throw new Exception("Spotify process is not running or was not found!");

int pid = p[0].Id;
int pid = GetSpotifyPid();

ISimpleAudioVolume volume = GetVolumeObject(pid);
if (volume == null)
Expand All @@ -50,11 +43,7 @@ internal static bool IsSpotifyMuted()

internal static void SetSpotifyVolume(float level)
{
Process[] p = Process.GetProcessesByName(SpotifyProcessName);
if (p.Length == 0)
throw new Exception("Spotify process is not running or was not found!");

int pid = p[0].Id;
int pid = GetSpotifyPid();

ISimpleAudioVolume volume = GetVolumeObject(pid);
if (volume == null)
Expand All @@ -69,11 +58,7 @@ internal static void SetSpotifyVolume(float level)

internal static void MuteSpotify(bool mute)
{
Process[] p = Process.GetProcessesByName(SpotifyProcessName);
if (p.Length == 0)
throw new Exception("Spotify process is not running or was not found!");

int pid = p[0].Id;
int pid = GetSpotifyPid();

ISimpleAudioVolume volume = GetVolumeObject(pid);
if (volume == null)
Expand All @@ -86,6 +71,20 @@ internal static void MuteSpotify(bool mute)
Marshal.ReleaseComObject(volume);
}

private static int GetSpotifyPid()
{
Process[] processes = Process.GetProcessesByName(SpotifyProcessName);
if (processes.Length == 0)
throw new Exception("Spotify process is not running or was not found!");

Process mainProc = processes.FirstOrDefault(o => o.MainWindowHandle != IntPtr.Zero);

if(mainProc == null)
throw new Exception("Spotify main-process is not running or was not found!");

return mainProc.Id;
}

private static ISimpleAudioVolume GetVolumeObject(int pid)
{
// get the speakers (1st render + multimedia) device
Expand Down