-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmartplay.py
175 lines (140 loc) · 4.45 KB
/
smartplay.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
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
# -*- coding: utf8 -*-
import begin
from colorama import Fore, Back, Style, init
from datetime import datetime
import musicbrainzngs as brainz
from mutagen.mp3 import MP3
import msvcrt
import os
from pygame import mixer
import random
import re
import time
_name = 'Smart Play!'
_version = "0.0.2"
init(autoreset=True)
brainz.set_useragent(_name, _version)
COLOR_COMBINATIONS = [
Fore.WHITE + Back.CYAN,
Fore.WHITE + Back.RED,
Fore.GREEN + Back.BLUE + Style.BRIGHT,
Fore.MAGENTA + Back.LIGHTGREEN_EX,
Fore.LIGHTRED_EX + Back.LIGHTWHITE_EX,
]
def colorize_text(text):
"Colorize printed text randomly"
return random.choice(COLOR_COMBINATIONS) + text
class MusicInfo(object):
def __init__(self, filename, filepath):
self.filename = filename
self.filepath = filepath
self._length = None
@property
def length(self):
if not self._length:
self._length = MP3(self.complete_path).info.length
return self._length
@property
def complete_path(self):
return os.path.join(self.filepath, self.filename)
def complement_info(self):
self._get_info_from_brainz()
def _get_info_from_brainz(self):
results = brainz.search_works(alias=self._get_alias())
try:
work = results['work-list'][0]
self.title = work.get('title', None)
self.artists = [
a['artist']['name']
for a in work['artist-relation-list']
if 'artist' in a]
except Exception:
self.title = None
self.artists = []
def _get_alias(self):
title = self.filename
start_number = re.match("([0-9])+", title)
if start_number:
title = title.replace(start_number.group(), "")
return self.filename \
.replace(".mp3", "") \
.replace("-", " ") \
.replace("_", " ") \
.replace(".", " ") \
.strip(" ")
def find_all_songs(path):
"Finds all MP3 songs under a folder (and its subfolders)"
all_songs = []
for root, _, files in os.walk(path):
for f in files:
if f.endswith(".mp3"):
all_songs.append(
MusicInfo(
filename=f,
filepath=root))
return all_songs
def select_song(all_songs):
"Select one of the songs randomly"
return random.choice(all_songs)
def play_song(music_info):
mixer.init()
mixer.music.load(music_info.complete_path)
mixer.music.play()
def pause_music():
mixer.music.pause()
def unpause_music():
mixer.music.unpause()
def print_info(music_info):
music_info.complement_info()
if music_info.title:
print(colorize_text("Music title is " + music_info.title))
for a in music_info.artists:
print(colorize_text("* " + a))
def restart_music(original_length):
global duration
unpause_music()
mixer.music.rewind()
duration = original_length
def wait_for_command_or_timeout(length):
'Wait for a valid command or timeout until finishes'
global duration
start_time = time.time()
paused = False
while True:
if msvcrt.kbhit():
key = msvcrt.getch().upper()
if key == b'N':
break
elif key == b'P' and not paused:
paused = True
pause_music()
elif key == b'C' and paused:
paused = False
unpause_music()
elif key == b'R':
paused = False
restart_music(length)
elif key == b'Q':
exit()
elif time.time() - start_time > duration:
break
time.sleep(0.5)
def log_text(text):
filename = 'log.txt'
with open(filename, 'a' if os.path.exists(filename) else 'w') as f:
f.write('[{}] {}\n'.format(
datetime.now().strftime('%Y-%m-%d %H:%M:%S'), text))
@begin.start
def main(folder: "Music folder", log=False):
global duration
print(colorize_text("{} v{}".format(_name, _version)))
print(colorize_text("[N]ext [P]ause [C]ontinue [R]estart [Q]uit"))
all_songs = find_all_songs(folder)
while True:
song = select_song(all_songs)
duration = song.length
print(colorize_text("Playing '{}'".format(song.filename)))
play_song(song)
if log:
log_text(song.complete_path)
wait_for_command_or_timeout(duration)