1
1
using System ;
2
2
using System . Diagnostics ;
3
+ using System . Linq ;
3
4
using System . Runtime . InteropServices ;
4
5
5
6
namespace SpotifyAPI . Local
6
7
{
7
- internal class VolumeMixerControl
8
+ internal static class VolumeMixerControl
8
9
{
9
10
private const String SpotifyProcessName = "spotify" ;
10
11
11
12
internal static float GetSpotifyVolume ( )
12
13
{
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 ( ) ;
18
15
19
16
ISimpleAudioVolume volume = GetVolumeObject ( pid ) ;
20
17
if ( volume == null )
@@ -30,11 +27,7 @@ internal static float GetSpotifyVolume()
30
27
31
28
internal static bool IsSpotifyMuted ( )
32
29
{
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 ( ) ;
38
31
39
32
ISimpleAudioVolume volume = GetVolumeObject ( pid ) ;
40
33
if ( volume == null )
@@ -50,11 +43,7 @@ internal static bool IsSpotifyMuted()
50
43
51
44
internal static void SetSpotifyVolume ( float level )
52
45
{
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 ( ) ;
58
47
59
48
ISimpleAudioVolume volume = GetVolumeObject ( pid ) ;
60
49
if ( volume == null )
@@ -69,11 +58,7 @@ internal static void SetSpotifyVolume(float level)
69
58
70
59
internal static void MuteSpotify ( bool mute )
71
60
{
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 ( ) ;
77
62
78
63
ISimpleAudioVolume volume = GetVolumeObject ( pid ) ;
79
64
if ( volume == null )
@@ -86,6 +71,20 @@ internal static void MuteSpotify(bool mute)
86
71
Marshal . ReleaseComObject ( volume ) ;
87
72
}
88
73
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
+
89
88
private static ISimpleAudioVolume GetVolumeObject ( int pid )
90
89
{
91
90
// get the speakers (1st render + multimedia) device
0 commit comments