forked from albertz/music-player
/
State.py
91 lines (78 loc) · 2.41 KB
/
State.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
from utils import *
from Song import Song
import appinfo
def loadQueue(state):
print "load queue"
def songs():
if state.curSong:
# We just started the player and we have a current song from persistant storage.
# Yield it now so that we begin playing with this song.
yield state.curSong
import os
from RandomFileQueue import RandomFileQueue
fileQueue = RandomFileQueue(
rootdir = os.path.expanduser("~/Music"),
fileexts = ["mp3", "ogg", "flac", "wma"])
while True:
f = fileQueue.getNextFile()
yield Song(f)
return songs()
from collections import deque
class RecentlyplayedList:
Limit = 10
def __init__(self, list=[], previous=None, index=0):
self.index = index
self.list = deque(list)
self.previous = None
def append(self, song):
if not song: return
self.list.append(song)
if len(self.list) >= self.Limit:
newList = PersistentObject(RecentlyplayedList, "recentlyplayed-%i.dat" % self.index, persistentRepr=True)
newList.index = self.index
newList.list = self.list
newList.previous = self.previous
newList.save()
self.index += 1
self.previous = newList
self.list = deque()
def __repr__(self):
return "RecentlyplayedList(list=%s, previous=%s, index=%i)" % (
betterRepr(self.list),
betterRepr(self.previous),
self.index)
def loadRecentlyplayedList(state):
return PersistentObject(RecentlyplayedList, "recentlyplayed.dat")
class PlayerEventCallbacks:
onSongChange = None
onSongFinished = None
onPlayingStateChange = None
def loadPlayer(state):
import ffmpeg
player = ffmpeg.createPlayer()
for e in [m for m in dir(PlayerEventCallbacks) if not m.startswith("_")]:
cb = EventCallback(targetQueue=state.updates, name=e)
setattr(PlayerEventCallbacks, e, cb)
setattr(player, e, cb)
player.queue = state.queue
return player
def playerMain():
state.player.playing = True
for ev,args,kwargs in state.updates.read():
if ev is PlayerEventCallbacks.onSongChange:
state.curSong = kwargs["newSong"]
state.curSong.save()
state.recentlyPlayedList.append(kwargs["oldSong"])
state.recentlyPlayedList.save()
pass # onPlayingStateChange
class State(object):
queue = initBy(loadQueue)
recentlyPlayedList = initBy(loadRecentlyplayedList)
curSong = initBy(lambda self: PersistentObject(Song, "cursong.dat"))
playState = oneOf(
"playing",
"paused"
)
updates = initBy(lambda self: OnRequestQueue())
player = initBy(loadPlayer)
state = State()