This repository has been archived by the owner on Jan 26, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
player.py
522 lines (518 loc) · 16.5 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
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
#!/usr/bin/env python
"""
#######################################################
# Python Music Player
# By Benjamin Urquhart
# VERSION: 2.4.3
This player is designed to play music on a Raspberry Pi,
but can be used on Windows and OSX.
OSX support is limited.
Don't expect good documentation for a little while.
#######################################################
"""
version = '2.4'
revision = '3'
######################################################
import datetime
import urllib
import urllib2
import os
import sys
import string
import tarfile
from threading import Thread as Process
#from multiprocessing import Process
from time import sleep
from random import randint
try:
import traceback
import requests
except ImportError:
pass
#####################################################
#connUser = False
threadUse = False
stop = False
skip = False
pause = False
play = False
debug = False
option = "n"
select = 0
current = ""
amount = 0
played = []
playlist = []
check = ""
width = 800
height = 600
console = False
text = ''
songNum = 1
kill = False
######################################################
# ############
print "Starting Python Music Player " + version + "." + revision #
# ############
######################################################
def mkdir(directory):
if not os.path.exists(directory):
os.makedirs(directory)
######################################################
def touch(path):
with open(path, 'a'):
os.utime(path, None)
######################################################
# The shutdown process
def shutdown():
try:
bcast("\n")
bcast("Stopping...")
pygame.mixer.music.stop()
"""
try:
conn.close()
s.close()
except:
LogErr()
pass
"""
log("Shutdown success")
log_file.close()
pygame.quit()
quit()
except:
log("An error occoured")
LogErr()
log_file.close()
pygame.quit()
quit()
######################################################
# Custom logging function
def log(string):
try:
if debug:
print "[Debug]: " + string
log_file.write("[Logger]: ")
log_file.write(string)
log_file.write("\n")
except:
pass
######################################################
def LogErr():
try:
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
log('')
log(''.join(line for line in lines))
if debug:
bcast("[Error]: " + ''.join(line for line in lines), True)
except:
pass
######################################################
def bcast(string, err=False):
try:
if err:
print string
else:
print "[Player]: " + string
#conn.send(string)
text = string
#display(string, background, screen)
except:
pass
######################################################
def updater():
log('Update requested; attempting...')
if update == 0:
bcast('No update found.')
log('No update found')
else:
bcast('Attempting to retrive tarball...')
try:
log('Connecting to ' + url +'...')
try:
r = requests.get('http://' + url)
status = r.status_code
except:
status = 200
LogErr()
if status == int(200):
try:
filename = urllib.urlretrieve('http://' + url + '/python/downloads/player/music-player-' + str(ver) + '.tar.gz', 'music-player-' + str(ver) + '.tar.gz')
except:
LogErr()
raise IOError
bcast('Installing...')
log('Download success')
log('Will now attempt to install update')
try:
mkdir('update')
os.rename("music-player-" + str(ver) + ".tar.gz", 'update/update.tar.gz')
os.chdir('update')
tar = tarfile.open("update.tar.gz")
tar.extractall()
tar.close()
os.remove('update.tar.gz')
os.chdir('..')
log('Success!')
bcast('Done!')
bcast("Move 'player.py' from the folder 'update' to: " + os.path.dirname(os.getcwd()))
except:
LogErr()
bcast('Installation failed')
else:
bcast('Server is down')
raise IOError
except:
LogErr()
bcast('Download failed')
######################################################
# To control the player remotely (non-functional)
def server():
try:
import socket
HOST = socket.gethostname()
PORT = 9000
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
LogErr()
try:
s.close()
except:
LogErr()
pass
s.listen(2)
print 'Started control server on ' + HOST + ':' + str(PORT)
except:
print "Couldn't create control server"
LogErr()
######################################################
# Get news updates
def news():
log("Getting news")
try:
news = urllib2.urlopen("http://" + url + "/news.txt")
news = news.read()
if news == '':
bcast("No News")
log("No News")
else:
bcast(news)
log(news)
except:
LogErr()
bcast("Couldn't get news updates", True)
######################################################
def control():
threadUse = True
option = ''
option = raw_input('> ')
try:
option = option.replace("\n", '')
option = option.lower()
if option == 'quit' or option == 'stop':
print "Use Control-C to quit"
#stop = True
#shutdown()
elif option == 'skip':
#skip = True
pygame.mixer.music.stop()
elif option == 'update':
#update = True
updater()
# Play/Pause indev
elif option == 'pause':
#pause = True
pygame.mixer.music.pause()
bcast('Paused')
elif option == 'play':
#play = True
pygame.mixer.music.play()
elif option == '':
option = ''
elif option == 'debug':
if debug == True:
print "Debug mode disabled"
debug = False
elif debug == False:
print "Debug mode enabled"
debug = True
elif option == "news":
news()
else:
bcast("Invalid command: " + option)
except:
LogErr()
sleep(0.1)
threadUse = False
###################################################
def control2():
try:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event == pygame.K_d:
print "Debug"
if debug:
debug = False
else:
debug = True
if event.key == pygame.K_SPACE or event.key == pygame.K_F11:
bcast("Pause")
if pause == True:
pygame.mixer.music.play()
pause = False
elif pause == False:
pygame.mixer.music.pause()
pause = True
if event.key == pygame.K_u:
bcast("Update")
updater()
if event.key == pygame.K_F12:
bcast("Skip")
pygame.mixer.music.stop()
if event.key == pygame.K_F10 or event.key == pygame.K_q:
bcast("Quit")
shutdown()
except:
LogErr()
sleep(0.2)
######################################################
mkdir('logs')
time = datetime.datetime.now()
try:
log_file = open("./logs/" + str(time), "w+")
except:
LogErr()
bcast("Failed to create log")
######################################################
"""
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
######################################################
def display(text):
screen.fill((225, 225, 225))
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((width/2),(height/2))
screen.blit(TextSurf, TextRect)
pygame.display.update()
pygame.display.flip()
"""
def display(text, background, screen):
font = pygame.font.Font("freesansbold", 36)
out = font.render(text, 1, (10, 10, 10))
textpos = out.get_rect()
textpos.centerx = background.get_rect().centerx
background.blit(out, textpos)
# Blit everything to the screen
screen.blit(background, (0, 0))
pygame.display.flip()
######################################################
#server()
######################################################
# Looking for pygame...
try:
import pygame
from pygame.locals import *
#import Screen
except ImportError:
LogErr()
try:
print "Downloading assets"
log('Pygame missing; getting installer')
osv = sys.platform
if osv == 'win32':
urllib.urlretrieve('https://pygame.org/ftp/pygame-1.9.1.win32-py2.7.msi', 'pygame-1.9.1.msi')
elif osv == 'darwin':
urllib.urlretrieve('https://pygame.org/ftp/pygame-1.9.1release-python.org-32bit-py2.7-macosx10.3.dmg', 'pygame-mac.dmg')
log('Success!')
elif osv == 'linux2' or 'cygwin':
print 'You are using linux or cygwin'
print "Use the command 'sudo pip install pygame' to download\nthe nessasary modules"
log(osv + ' detected; pip installer recommended')
else:
print 'Unrecognized os: ' + osv
try:
urllib.urlretrieve('http://' + url + '/pygame.tar.gz', 'pygame.tar.gz')
tar = tarfile.open("pygame.tar.gz")
tar.extractall()
tar.close()
os.remove('pygame.tar.gz')
except:
LogErr()
print "Failed to get assets"
exit()
print 'Please run the installer that has been dropped into the ' + os.path.dirname(os.getcwd()) + ' folder'
except:
print 'Failed to get assets'
print "Please install the 'pygame' module manually at pygame.org"
LogErr()
shutdown()
exit()
#######################################################
# Load pygame module
try:
pygame.init()
pygame.mixer.init()
#pygame.font.init()
log('Pygame initialized')
except:
bcast("Couldn't run pygame.init()", True)
log("pygame.init() failed")
LogErr()
#######################################################
try:
if len(sys.argv) > 1:
i = 1
while i < len(sys.argv):
arg = sys.argv[i]
if arg == "--console" or arg == "-c":
console = True
elif arg == "--verbose" or arg == "-v":
debug = True
elif arg == "-f" or arg == "--file":
pygame.init()
try:
pygame.mixer.music.load(sys.argv[i+1])
print "Now Playing: " + sys.argv[i+1]
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
continue
kill = True
except:
LogErr()
print "There was an error playing the file"
kill = True
elif arg == "-h" or arg == "--help":
print 'Plays music in the "Music" folder within the current directory\n'
print "Usage: " + sys.argv[0] + " [-hvc] [-f <filepath>]"
print "Options: "
print "\t -h, --help\t Displays this help text"
print "\t -v, --verbose\t Displays extra information"
print "\t -c, --console\t Disables Pygame screen (text-only mode)"
print "\t -f, --file\t Plays the file at the filepath specified"
print "\nExamples: \n\t " + sys.argv[0] + " -v -c -f /sample/file/path/foo.bar"
print "\t " + sys.argv[0] + " -f foo.bar"
kill = True
i = i + 1
except:
pass
if kill:
exit()
######################################################
# Checking for updates...
url = "4hmediaproductions.com"
update = 0
try:
log('Checking for updates...')
log('Getting info from ' + url)
ver = urllib2.urlopen('http://' + url + '/version.txt')
rev = urllib2.urlopen('http://' + url + '/rev.txt')
ver = ver.read()
rev = rev.read()
if float(ver) > float(version):
log('Update found!')
bcast("Python Music Player " + ver + " is availible")
bcast("Type update at the prompt to download")
update = 1
elif float(ver) < float(version):
log('Indev vesion in use')
bcast('Indev version in use')
elif int(rev) > int(revision) and float(ver) == float(version):
log('New revision found!')
bcast('Revision ' + str(rev) + ' is availible')
bcast('Type update at the prompt to download')
update = 1
elif float(ver) == float(version):
log('No update found')
bcast('No update found')
except:
bcast('Failed to check for updates', True)
LogErr()
log('Update check failed')
######################################################
mkdir('Music')
log("Player starting...")
news()
######################################################
try:
if console == False:
screen = pygame.display.set_mode((1000, 200))
pygame.display.set_caption("Music Player")
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((250, 250, 250))
except:
bcast("Display error, console mode active", True)
log("Display error")
LogErr()
console = True
log("Player started")
# Check the Music folder for tracks
sound_data = os.listdir('./Music')
try:
for i in sound_data:
playlist.append(i)
i = 0
amount = len(playlist)
log(str(amount) + " Songs found")
if amount == 0:
bcast('No music found!')
shutdown()
bcast("Number of songs: " + str(amount))
#######################################################
# Play the music
while i != amount:
select = randint(0, amount - 1)
if option.lower() == "y":
for i in song:
current = i
option = "n"
else:
current = playlist[select]
#current = current.replace("\n", "")
if current not in played:
# Try to load the track
bcast("Now Playing: " + current + " (" + str(songNum) + " out of " + str(amount) + ")")
log("Song " + str(songNum) + " out of " + str(amount))
try:
log("Loading '" + current + "'")
pygame.mixer.music.load("./Music/" + current)
log('Now Playing: ' + current)
except:
bcast("Couldn't play " + current)
#######################################################
# Play loaded track
pygame.mixer.music.play()
# Take user input for controlling player
while pygame.mixer.music.get_busy():
if console == False:
#font = pygame.font.Font(None, 36)
#out = font.render(text, 1, (10, 10, 10))
#textpos = out.get_rect()
##textpos.centerx = background.get_rect().centerx
screen.blit(background, (0, 0))
#pygame.display.flip()
control2()
else:
t = Process(None, control())
t.daemon = False
t.start()
#######################################################
if not current in played:
played.append(current)
i = i + 1
sleep(0.2)
songNum = songNum + 1
bcast("All songs have been played!")
log('All songs have been played')
shutdown()
#######################################################
except:
LogErr()
shutdown()