forked from JohnnyCrazy/SpotifyAPI-NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpotifyLocalAPI.cs
More file actions
337 lines (305 loc) · 12.5 KB
/
SpotifyLocalAPI.cs
File metadata and controls
337 lines (305 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
using SpotifyAPI.Local.Models;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Timers;
namespace SpotifyAPI.Local
{
public class SpotifyLocalAPI
{
[DllImport("user32.dll")]
private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);
private bool _listenForEvents;
public bool ListenForEvents
{
get
{
return _listenForEvents;
}
set
{
_listenForEvents = value;
_eventTimer.Enabled = value;
}
}
private ISynchronizeInvoke _synchronizingObject;
public ISynchronizeInvoke SynchronizingObject
{
get
{
return _synchronizingObject;
}
set
{
_synchronizingObject = value;
_eventTimer.SynchronizingObject = value;
}
}
private const byte VkMediaNextTrack = 0xb0;
private const byte VkMediaPrevTrack = 0xb1;
private const int KeyeventfExtendedkey = 0x1;
private const int KeyeventfKeyup = 0x2;
private readonly RemoteHandler _rh;
private readonly Timer _eventTimer;
private StatusResponse _eventStatusResponse;
public event EventHandler<TrackChangeEventArgs> OnTrackChange;
public event EventHandler<PlayStateEventArgs> OnPlayStateChange;
public event EventHandler<VolumeChangeEventArgs> OnVolumeChange;
public event EventHandler<TrackTimeChangeEventArgs> OnTrackTimeChange;
public SpotifyLocalAPI()
{
_rh = new RemoteHandler();
_eventTimer = new Timer
{
Interval = 50,
AutoReset = false,
Enabled = false
};
_eventTimer.Elapsed += ElapsedTick;
}
private void ElapsedTick(object sender, ElapsedEventArgs e)
{
if (_eventStatusResponse == null)
{
_eventStatusResponse = GetStatus();
_eventTimer.Start();
return;
}
StatusResponse newStatusResponse = GetStatus();
if (newStatusResponse == null)
{
_eventTimer.Start();
return;
}
if (!newStatusResponse.Running && newStatusResponse.Track == null)
{
_eventTimer.Start();
return;
}
if (newStatusResponse.Track != null && _eventStatusResponse.Track != null)
{
if (newStatusResponse.Track.TrackResource?.Name != _eventStatusResponse.Track.TrackResource?.Name)
{
OnTrackChange?.Invoke(this, new TrackChangeEventArgs()
{
OldTrack = _eventStatusResponse.Track,
NewTrack = newStatusResponse.Track
});
}
}
if (newStatusResponse.Playing != _eventStatusResponse.Playing)
{
OnPlayStateChange?.Invoke(this, new PlayStateEventArgs()
{
Playing = newStatusResponse.Playing
});
}
if (newStatusResponse.Volume != _eventStatusResponse.Volume)
{
OnVolumeChange?.Invoke(this, new VolumeChangeEventArgs()
{
OldVolume = _eventStatusResponse.Volume,
NewVolume = newStatusResponse.Volume
});
}
if (newStatusResponse.PlayingPosition != _eventStatusResponse.PlayingPosition)
{
OnTrackTimeChange?.Invoke(this, new TrackTimeChangeEventArgs()
{
TrackTime = newStatusResponse.PlayingPosition
});
}
_eventStatusResponse = newStatusResponse;
_eventTimer.Start();
}
/// <summary>
/// Connects with Spotify. Needs to be called before all other SpotifyAPI functions
/// </summary>
/// <returns>Returns true, if it was successful, false if not</returns>
public Boolean Connect()
{
return _rh.Init();
}
/// <summary>
/// Update and returns the new StatusResponse from the Spotify-Player
/// </summary>
/// <returns>An up-to-date StatusResponse</returns>
public StatusResponse GetStatus()
{
return _rh.GetNewStatus();
}
/// <summary>
/// Mutes Spotify (Requires Windows 7 or newer)
/// </summary>
public void Mute()
{
//Windows < Windows Vista Check
if (Environment.OSVersion.Version.Major < 6)
throw new NotSupportedException("This feature is only available on Windows 7 or newer");
//Windows Vista Check
if (Environment.OSVersion.Version.Major == 6)
if(Environment.OSVersion.Version.Minor == 0)
throw new NotSupportedException("This feature is only available on Windows 7 or newer");
VolumeMixerControl.MuteSpotify(true);
}
/// <summary>
/// Unmutes Spotify (Requires Windows 7 or newer)
/// </summary>
public void UnMute()
{
//Windows < Windows Vista Check
if (Environment.OSVersion.Version.Major < 6)
throw new NotSupportedException("This feature is only available on Windows 7 or newer");
//Windows Vista Check
if (Environment.OSVersion.Version.Major == 6)
if (Environment.OSVersion.Version.Minor == 0)
throw new NotSupportedException("This feature is only available on Windows 7 or newer");
VolumeMixerControl.MuteSpotify(false);
}
/// <summary>
/// Checks whether Spotify is muted in the Volume Mixer control (required Windows 7 or newer)
/// </summary>
/// <returns>Null if an error occured, otherwise the muted state</returns>
public bool IsSpotifyMuted()
{
//Windows < Windows Vista Check
if (Environment.OSVersion.Version.Major < 6)
throw new NotSupportedException("This feature is only available on Windows 7 or newer");
//Windows Vista Check
if (Environment.OSVersion.Version.Major == 6)
if (Environment.OSVersion.Version.Minor == 0)
throw new NotSupportedException("This feature is only available on Windows 7 or newer");
return VolumeMixerControl.IsSpotifyMuted();
}
/// <summary>
/// Sets the Volume Mixer volume (requires Windows 7 or newer)
/// </summary>
/// <param name="volume">A value between 0 and 100</param>
public void SetSpotifyVolume(float volume = 100)
{
//Windows < Windows Vista Check
if (Environment.OSVersion.Version.Major < 6)
throw new NotSupportedException("This feature is only available on Windows 7 or newer");
//Windows Vista Check
if (Environment.OSVersion.Version.Major == 6)
if (Environment.OSVersion.Version.Minor == 0)
throw new NotSupportedException("This feature is only available on Windows 7 or newer");
if (volume < 0 || volume > 100)
throw new ArgumentOutOfRangeException(nameof(volume));
VolumeMixerControl.SetSpotifyVolume(volume);
}
/// <summary>
/// Return the Volume Mixer volume of Spotify (requires Windows 7 or newer)
/// </summary>
/// <returns>Null if an error occured, otherwise a float between 0 and 100</returns>
public float GetSpotifyVolume()
{
//Windows < Windows Vista Check
if (Environment.OSVersion.Version.Major < 6)
throw new NotSupportedException("This feature is only available on Windows 7 or newer");
//Windows Vista Check
if (Environment.OSVersion.Version.Major == 6)
if (Environment.OSVersion.Version.Minor == 0)
throw new NotSupportedException("This feature is only available on Windows 7 or newer");
return VolumeMixerControl.GetSpotifyVolume();
}
/// <summary>
/// Pause function
/// </summary>
public void Pause()
{
_rh.SendPauseRequest();
}
/// <summary>
/// Play function
/// </summary>
public void Play()
{
_rh.SendPlayRequest();
}
/// <summary>
/// Simulates a KeyPress
/// </summary>
/// <param name="keyCode">The keycode for the represented Key</param>
internal void PressKey(byte keyCode)
{
keybd_event(keyCode, 0x45, KeyeventfExtendedkey, 0);
keybd_event(keyCode, 0x45, KeyeventfExtendedkey | KeyeventfKeyup, 0);
}
/// <summary>
/// Plays a Spotify URI within an optional context.
/// </summary>
/// <param name="uri">The Spotify URI</param>
/// <param name="context">The context in which to play the specified <paramref name="uri"/>. </param>
/// <remarks>
/// Contexts are basically a queue in spotify. a song can be played within a context, meaning that hitting next / previous would lead to another song. Contexts are leveraged by widgets as described in the "Multiple tracks player" section of the following documentation page: https://developer.spotify.com/technologies/widgets/spotify-play-button/
/// </remarks>
public void PlayURL(string uri, string context = "")
{
_rh.SendPlayRequest(uri, context);
}
/// <summary>
/// Adds a Spotify URI to the Queue
/// </summary>
/// <param name="uri">The Spotify URI</param>
[Obsolete("This method doesn't work with the current spotify version.")]
public void AddToQueue(string uri)
{
_rh.SendQueueRequest(uri);
}
/// <summary>
/// Skips the current song (Using keypress simulation)
/// </summary>
public void Skip()
{
PressKey(VkMediaNextTrack);
}
/// <summary>
/// Emulates the "Previous" Key (Using keypress simulation)
/// </summary>
public void Previous()
{
PressKey(VkMediaPrevTrack);
}
/// <summary>
/// Checks if Spotify is running
/// </summary>
/// <returns>True, if it's running, false if not</returns>
public static Boolean IsSpotifyRunning()
{
return Process.GetProcessesByName("spotify").Length >= 1;
}
/// <summary>
/// Checks if Spotify's WebHelper is running (Needed for API Calls)
/// </summary>
/// <returns>True, if it's running, false if not</returns>
public static Boolean IsSpotifyWebHelperRunning()
{
return Process.GetProcessesByName("spotifywebhelper").Length >= 1;
}
/// <summary>
/// Runs Spotify
/// </summary>
public static void RunSpotify()
{
if (!IsSpotifyRunning() && File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"spotify\spotify.exe")))
Process.Start(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"spotify\spotify.exe"));
}
/// <summary>
/// Runs Spotify's WebHelper
/// </summary>
public static void RunSpotifyWebHelper()
{
if (!IsSpotifyWebHelperRunning() && File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"spotify\data\spotifywebhelper.exe")))
{
Process.Start(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"spotify\data\spotifywebhelper.exe"));
}
else if (!IsSpotifyWebHelperRunning() && File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"spotify\spotifywebhelper.exe")))
{
Process.Start(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"spotify\spotifywebhelper.exe"));
}
}
}
}