-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplayer.py
219 lines (178 loc) · 6.48 KB
/
player.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
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
import os
import time
import pprint
import cmd
import threading
from sys import exit
from queue import Queue
from subprocess import call
from env import get_environment
from mutagen.easyid3 import EasyID3
from utils import get_filename
"""Windows doesn't have a readline package :("""
try:
import readline
except ImportError:
import pyreadline as readline
if os.name == "nt":
from winplayer import MusicPlayer
else:
raise Exception("Not supported on this operation system at the moment")
class Enum(set):
def __getattr__(self, name):
if name in self:
return name
raise AttributeError
class PlayerShell(cmd.Cmd):
intro = 'Dumb Python Music Player. Type "help" or "?"" to list commands.\n'
prompt = '> '
token = prompt
# Internals
player = MusicPlayer()
playlist = Queue()
pp = pprint.PrettyPrinter(indent=4)
running = True
types = Enum(["PLAY", "PAUSE", "CLOSE", "RESUME"])
messages = Queue()
environment = get_environment()
current = None
repeat = False
def preloop(self):
self.chdir(self.environment['music_home'])
consumer = threading.Thread(target=self.consumer_player)
consumer.daemon = True
consumer.start()
def do_exit(self, arg):
"""Stop playing, and exit."""
self.messages.put(self.types.CLOSE)
self.running = False
return True
def do_repeat(self, arg):
"""Toggles playlist repeating"""
self.repeat = not self.repeat
val = "on" if self.repeat else "off"
print("Repeat is now %s" % val)
def do_cd(self, arg):
"""Change directory to the argument specified"""
# shitty windows hack for "My" in the directory
if os.name == "nt":
if "My " in arg:
arg.replace("My ", "")
if os.path.isdir(arg):
self.chdir(arg)
else:
print("%s is not a valid directory." % arg)
def complete_cd(self, text, line, begidx, endidx):
return self.complete_helper(text, line, begidx, endidx)
def do_ls(self, arg):
"""List and print the current directory"""
call("ls")
# playlist options
# TODO: can we group these better?
def do_add(self, arg):
"""Adds a song to the playlist specified as the argument to this command"""
f = get_filename(arg)
if f:
self.playlist.put(f)
else:
print("Not a valid selection to add to the playlist.")
def complete_add(self, text, line, begidx, endidx):
return self.complete_helper(text, line, begidx, endidx)
def do_addall(self, arg):
"""Adds all songs in the current directory to the playlist, not recursively"""
for song in self.list():
f = get_filename(song)
if f:
self.playlist.put(f)
def do_clear(self, arg):
"""Clears the entire playlist"""
self.playlist = Queue()
def do_show(self, arg):
"""Prints out the current song, if one is playing"""
if self.current is not None:
audio = EasyID3(self.current)
print("%s - %s" % (audio['title'][0], audio['album'][0]))
else:
print("There is no song currently playing.")
def do_showall(self, arg):
"""Prints out the entire playlist"""
for queued in self.playlist.queue:
audio = EasyID3(queued)
print("%s - %s" % (audio['title'][0], audio['album'][0]))
# song options
# TODO: Is there a logical grouping of functionality here? And if so, how do we do that in the cmd module?
def do_resume(self, arg):
"""Resume a paused song"""
self.messages.put(self.types.RESUME)
def do_pause(self, arg):
"""Pause a currently playing song"""
self.messages.put(self.types.PAUSE)
def do_skip(self, arg):
"""Stop the current song and play the next one in the playlist if it exists"""
# By simply closing, our background thread will start the next song if there is one
self.messages.put(self.types.CLOSE)
def do_stop(self, arg):
"""Stop playing the current song and clear playlist"""
self.messages.put(self.types.CLOSE)
self.playlist = Queue()
# helper methods
def list(self):
return os.listdir(".")
def cwd(self):
return os.getcwd()
def chdir(self, dir):
os.chdir(dir)
self.prompt = self.cwd() + '\n' + self.token
def complete_helper(self, text, line, begidx, endidx):
current_directory = self.list()
if text:
mline = line.partition(' ')[2]
offs = len(mline) - len(text)
# mline = mline.encode("utf8")
return [
s[offs:] for s in current_directory
if s.startswith(mline)
]
else:
return current_directory
def _get_next(self):
finished_song = self.current
song = self.playlist.get()
self.player.play_song(song)
self.current = song
if self.repeat and finished_song is not None:
self.playlist.put(finished_song)
def consumer_player(self):
while self.running:
# interrupt to modify the current song somehow
if not self.messages.empty():
_cmd = self.messages.get()
if _cmd == self.types.PLAY:
if not self.playlist.empty():
self._get_next()
elif _cmd == self.types.CLOSE:
self.player.close_song()
if not self.repeat:
self.current = None
elif _cmd == self.types.PAUSE:
self.player.pause_song()
elif _cmd == self.types.RESUME:
self.player.resume_song()
err_length, buf_length = self.player.length()
err_position, buf_position = self.player.position()
# we might be finished playing the current song
try:
position = int(buf_position)
total_time = int(buf_length)
if position >= total_time:
self.player.close_song()
if not self.playlist.empty():
self._get_next()
except ValueError:
if not self.playlist.empty():
self._get_next()
time.sleep(1)
def main():
PlayerShell().cmdloop()
if __name__ == "__main__":
exit(main())