11using System ;
22using System . Diagnostics ;
3+ using System . Linq ;
34using System . Runtime . InteropServices ;
45
56namespace SpotifyAPI . Local
67{
7- internal class VolumeMixerControl
8+ internal static class VolumeMixerControl
89 {
910 private const String SpotifyProcessName = "spotify" ;
1011
1112 internal static float GetSpotifyVolume ( )
1213 {
13- Process [ ] p = Process . GetProcessesByName ( SpotifyProcessName ) ;
14- if ( p . Length == 0 )
15- throw new Exception ( "Spotify process is not running or was not found!" ) ;
16-
17- int pid = p [ 0 ] . Id ;
14+ int pid = GetSpotifyPid ( ) ;
1815
1916 ISimpleAudioVolume volume = GetVolumeObject ( pid ) ;
2017 if ( volume == null )
@@ -30,11 +27,7 @@ internal static float GetSpotifyVolume()
3027
3128 internal static bool IsSpotifyMuted ( )
3229 {
33- Process [ ] p = Process . GetProcessesByName ( SpotifyProcessName ) ;
34- if ( p . Length == 0 )
35- throw new Exception ( "Spotify process is not running or was not found!" ) ;
36-
37- int pid = p [ 0 ] . Id ;
30+ int pid = GetSpotifyPid ( ) ;
3831
3932 ISimpleAudioVolume volume = GetVolumeObject ( pid ) ;
4033 if ( volume == null )
@@ -50,11 +43,7 @@ internal static bool IsSpotifyMuted()
5043
5144 internal static void SetSpotifyVolume ( float level )
5245 {
53- Process [ ] p = Process . GetProcessesByName ( SpotifyProcessName ) ;
54- if ( p . Length == 0 )
55- throw new Exception ( "Spotify process is not running or was not found!" ) ;
56-
57- int pid = p [ 0 ] . Id ;
46+ int pid = GetSpotifyPid ( ) ;
5847
5948 ISimpleAudioVolume volume = GetVolumeObject ( pid ) ;
6049 if ( volume == null )
@@ -69,11 +58,7 @@ internal static void SetSpotifyVolume(float level)
6958
7059 internal static void MuteSpotify ( bool mute )
7160 {
72- Process [ ] p = Process . GetProcessesByName ( SpotifyProcessName ) ;
73- if ( p . Length == 0 )
74- throw new Exception ( "Spotify process is not running or was not found!" ) ;
75-
76- int pid = p [ 0 ] . Id ;
61+ int pid = GetSpotifyPid ( ) ;
7762
7863 ISimpleAudioVolume volume = GetVolumeObject ( pid ) ;
7964 if ( volume == null )
@@ -86,6 +71,20 @@ internal static void MuteSpotify(bool mute)
8671 Marshal . ReleaseComObject ( volume ) ;
8772 }
8873
74+ private static int GetSpotifyPid ( )
75+ {
76+ Process [ ] processes = Process . GetProcessesByName ( SpotifyProcessName ) ;
77+ if ( processes . Length == 0 )
78+ throw new Exception ( "Spotify process is not running or was not found!" ) ;
79+
80+ Process mainProc = processes . FirstOrDefault ( o => o . MainWindowHandle != IntPtr . Zero ) ;
81+
82+ if ( mainProc == null )
83+ throw new Exception ( "Spotify main-process is not running or was not found!" ) ;
84+
85+ return mainProc . Id ;
86+ }
87+
8988 private static ISimpleAudioVolume GetVolumeObject ( int pid )
9089 {
9190 // get the speakers (1st render + multimedia) device
0 commit comments