-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcurrent_playing.py
59 lines (51 loc) · 2.55 KB
/
current_playing.py
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
import asyncio
import os
import json
from winrt.windows.media.control import \
GlobalSystemMediaTransportControlsSessionManager as MediaManager
from winrt.windows.storage.streams import \
DataReader, Buffer, InputStreamOptions
async def get_media_info():
sessions = await MediaManager.request_async()
# This source_app_user_model_id check and if statement is optional
# Use it if you want to only get a certain player/program's media
# (e.g. only chrome.exe's media not any other program's).
# To get the ID, use a breakpoint() to run sessions.get_current_session()
# while the media you want to get is playing.
# Then set TARGET_ID to the string this call returns.
current_session = sessions.get_current_session()
if current_session: # there needs to be a media session running
info = await current_session.try_get_media_properties_async()
# song_attr[0] != '_' ignores system attributes
info_dict = {song_attr: info.__getattribute__(song_attr) for song_attr in dir(info) if song_attr[0] != '_'}
# converts winrt vector to list
info_dict['genres'] = list(info_dict['genres'])
# create the current_media_info dict with the earlier code first
thumb_stream_ref = info_dict['thumbnail']
try:
filename="./static/media_thumb.jpg"
if os.path.exists(filename):
os.remove(filename)
# 5MB (5 million byte) buffer - thumbnail unlikely to be larger
thumb_read_buffer = Buffer(5000000)
await read_stream_into_buffer(thumb_stream_ref, thumb_read_buffer)
buffer_reader = DataReader.from_buffer(thumb_read_buffer)
byte_buffer = buffer_reader.read_bytes(thumb_read_buffer.length)
if not os.path.exists('static'):
os.makedirs('static')
filename="./static/media_thumb.jpg"
if not len(bytearray(byte_buffer)) ==0:
with open(filename, 'wb+') as fobj:
fobj.write(bytearray(byte_buffer))
info_dict["thumbnail"]=filename[1:]
except Exception as e:
# print(e)
# print("something went wrong with getting thumbnail")
info_dict["thumbnail"]=" "
return info_dict
return None
async def read_stream_into_buffer(stream_ref, buffer):
readable_stream = await stream_ref.open_read_async()
readable_stream.read_async(buffer, buffer.capacity, InputStreamOptions.READ_AHEAD)
if __name__ == '__main__':
print(json.dumps(asyncio.run(get_media_info())))