-
Notifications
You must be signed in to change notification settings - Fork 0
/
MusicInfo.py
105 lines (84 loc) · 2.92 KB
/
MusicInfo.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
import json
import os
from Song import Song
class MusicInfo():
MUSIC_EXTENSIONS = {'mp3'}
def __init__(self, musicPath):
self.musicPath = musicPath
self.musicFiles = []
self.playList = []
self.currentSong = None
self.loadMusic()
self.playListFile = "{}/playlist.cfg".format(self.musicPath)
self.loadPlayList()
def loadMusic(self):
it = os.scandir(self.musicPath)
for entry in it:
if not entry.name.startswith('.') and entry.is_file() and entry.name.rsplit('.', 1)[1].lower() in self.MUSIC_EXTENSIONS:
self.addSong(entry.path)
def addSong(self, filePath):
self.musicFiles.append(Song(filePath))
def loadPlayList(self):
if os.path.exists(self.playListFile):
if os.path.getsize(self.playListFile) > 0:
with open(self.playListFile, 'r') as filePlaylist:
playListNames = json.load(filePlaylist)
for playListName in playListNames:
tmpSong = self.getSong(playListName, True)
if tmpSong:
self.playList.append(tmpSong)
self.updatePlayListOrder(playListNames)
def addPlayList(self, name):
tmpSong = self.getSong(name, True)
if tmpSong:
self.playList.append(tmpSong)
def updatePlayList(self, songNames):
for songName in songNames:
if songName not in self.listPlayList():
self.addPlayList(songName)
for songName in self.listPlayList():
if songName not in songNames:
tmpSong = self.getPlayListItem(songName, True)
tmpSong.removeNext()
self.musicFiles.append(tmpSong)
self.updatePlayListOrder(songNames)
with open(self.playListFile, 'w') as filePlaylist:
json.dump(self.listPlayList(), filePlaylist, indent=2, separators=(',', ': '))
def updatePlayListOrder(self, songNames):
for i, songName in enumerate(songNames):
if i == len(songNames) - 1:
self.getPlayListItem(songName).setNext(i, self.getPlayListItem(songNames[0]))
else:
self.getPlayListItem(songName).setNext(i, self.getPlayListItem(songNames[i + 1]))
self.playList.sort(key=lambda x: x.order)
def listMusic(self):
tmpList = []
for song in self.musicFiles:
tmpList.append(song.name)
return tmpList
def listPlayList(self):
tmpList = []
for song in self.playList:
tmpList.append(song.name)
return tmpList
def getSong(self, name, pop=False):
for i, x in enumerate(self.musicFiles):
if x.name == name:
if pop:
return self.musicFiles.pop(i)
else:
return x
return None
def getPlayListItem(self, name, pop=False):
for i, x in enumerate(self.playList):
if x.name == name:
if pop:
return self.playList.pop(i)
else:
return x
return None
def setCurrentSong(self, name):
tmpSong = self.getSong(name)
if not tmpSong:
tmpSong = self.getPlayListItem(name)
self.currentSong = tmpSong