-
Notifications
You must be signed in to change notification settings - Fork 1
/
music.py
executable file
·555 lines (393 loc) · 15.5 KB
/
music.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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
from tkinter import * # GUI
from playsound import playsound # play audio
import os
import copy # Make a deep copy of a variable
import random
import vlc # play audio
# from pydub import AudioSegment
# from pydub.playback import play
import keyboard # Look for pressed key
import time # Includes sleep()
from link import LinkList, Node
from database import MusicDatabase
class MusicLibrary:
"""
def __init__(self, WIN_WIDTH, WIN_HEIGHT):
# NOTE: This init() is for GUI use
# Create a new window
self.musicWindow = Toplevel()
self.musicWindow.geometry("{}x{}".format(WIN_WIDTH, WIN_HEIGHT))
self.musicWindow.title("Music Library")
# Create a dictionary dedicated to artist
self.musicLibraryDict = dict()
# Gather all songs inside the device and add them to self.musicLibraryDict{}
self.totalSongs = 0
self.scanMusicDirectory()
# Create a link list of all the music in sorted order
self.finalMusicLinkList = LinkList()
self.organizeMusicLibrary()
self.finalMusicLinkList.size = self.totalSongs # Manually enter link list size
# Create a scrollable list
self.listBox = Listbox(self.musicWindow, selectmode=BROWSE) # <= BROWSE allows the user to scroll the list and only select 1 item
self.listBox.pack()
self.populateListBox()
"""
"""
NOTE: music_library structure:
Key | Value
--------------------------
Artist's name | [
{Album 1: Head node to 1st song},
{Album 2: Head node to 1st song},
{Album 3: Head node to 1st song},
]
"""
def __init__(self):
# NOTE: This init() is for command line use
# # Create a dictionary dedicated to artist
# self.musicLibraryDict = dict()
# # Gather all songs inside the device and add them to self.musicLibraryDict{}
# self.totalSongs = 0
# self.scanMusicDirectory()
# # Create a link list of all the music in sorted order
# self.finalMusicLinkList = LinkList()
# self.organizeMusicLibrary()
# self.finalMusicLinkList.size = self.totalSongs # Manually enter link list size
# Initialize class and connect to database
self.db = MusicDatabase()
# Save music in database
self.addMusicToDatabase()
def entryMsg(self, location):
# OBJECTIVE: Display a message whenever the user enters a new window
location = "Window: {}".format(location)
print("\n{}\n{}\n{}\n".format("=" * len(location), location, "=" * len(location)))
def errorMsg(self, msg):
# OBJECTIVE: Print a custom message if an exception or error rises
print("ERROR: {}".format(msg))
def addRemainingNodes(self, newLinkList, headA):
# OBJECTIVE: Add remaining nodes to from old link list to newLinkList
# print("Adding remaining nodes")
while headA != None:
newLinkList.addNode(headA.data)
# print(headA.data)
headA = headA.next
return newLinkList
def mergeTwoSortedLinkList(self, headA, headB):
# OBJECTIVE: Merge 2 sorted link list to one by calling functions from LinkList class
# link: https://www.geeksforgeeks.org/merge-sort-for-linked-list/
# Create a new link list
newLinkList = LinkList()
while True:
# If either link list is empty, add all elements from the other link list
if headA == None:
newLinkList = self.addRemainingNodes(newLinkList, headB)
break
if headB == None:
newLinkList = self.addRemainingNodes(newLinkList, headA)
break
# Compare nodes from both link list to see which goes first in sorted order
if headA.data <= headB.data:
# print("Adding A ")
# Update pointers
newLinkList.addNode(headA.data)
# Update headA
headA = headA.next
else:
# print("Adding B ")
# Update pointers
newLinkList.addNode(headB.data)
# Update headB
headB = headB.next
return newLinkList
def playSongFromLinkList(self, selectedLinkList):
# OBJECTIVE: Open a new window when a song has been selected from a link list
# Print song being played
self.entryMsg("Music Player")
# Get head node
currNode = selectedLinkList.getHead()
# While currNode isn't none, continue to show playSongFromLinkList
# Exit function once currNode is none
while currNode != None:
# Print what song is playing and what options are available
print("\nNow Playing: {}".format(currNode.data))
option = input("< |>| > -1: ")
# Narrow down options
if option == "<":
currNode = currNode.prev
elif option == "|>|":
option = "Pause/Play"
elif option == ">":
currNode = currNode.next
elif option == "-1":
return
else:
self.errorMsg("Invalid entry!")
continue
def playSongFromSortedLinkList(self, selectedNode):
# OBJECTIVE: Open a new window when a song has been selected
# Print song being played
self.entryMsg("Music Player")
# While currNode isn't none, continue to show playSongFromLinkList
# Exit function once currNode is none
while selectedNode != None:
# Print what song is playing and what options are available
print("\nNow Playing: {}".format(selectedNode.data))
option = input("< |>| > -1: ")
# Narrow down options
if option == "<":
selectedNode = selectedNode.prev
elif option == "|>|":
option = "Pause/Play"
elif option == ">":
selectedNode = selectedNode.next
elif option == "-1":
return
else:
self.errorMsg("Invalid entry!")
continue
def shuffleMusic(self):
# OBJECTIVE: Pick a random number and play song at selected position
print("Shuffling music")
# Create a list filled with random numbers
randomNumbers = list()
while len(randomNumbers) != self.finalMusicLinkList.size:
# Generate a unique random number and add it to list
r = random.randint(1, self.finalMusicLinkList.size)
if r not in randomNumbers:
randomNumbers.append(r)
# Add data in Nth position to shuffle link list
newLinkList = LinkList()
for pos in randomNumbers:
result = self.finalMusicLinkList.binarySearchForPosition(self.finalMusicLinkList.getHead(), self.finalMusicLinkList.getTail(), pos)
newLinkList.addNode(result)
# Delete list and sent link list to playSongFromLinkList()
del randomNumbers
self.playSongFromLinkList(newLinkList)
def showMusicLibraryWindow(self):
# OBJECTIVE: List all songs inside the device onto the window in alphabetical order
self.entryMsg("Music Library")
# Select music to play
print("Enter -1 to go back")
while True:
# Print music library
self.finalMusicLinkList.printForward()
# Raise exception if musicSelected cannot cast to int
try:
musicSelected = int(input("\nPlay song #: "))
except:
self.errorMsg("Numbers only!")
else:
# Skip to next iteration, if invalid entry was entered
if musicSelected == -1:
return
if (musicSelected > self.finalMusicLinkList.size) or (musicSelected <= 0):
self.errorMsg("Invalid entry!")
continue
# Get song from nth position
nodeWithSong = self.finalMusicLinkList.binarySearchForNode(self.finalMusicLinkList.getHead(), self.finalMusicLinkList.getTail(), musicSelected)
self.playSongFromSortedLinkList(nodeWithSong)
# self.finalMusicLinkList.printForward()
def organizeMusicLibrary(self):
# OBJECTIVE: Iterate dictionary and add music to a sorted link list. Return head of link list
print("Creating 1 link list with all the music together in sorted order")
# Create a list to hold all head nodes inside self.music.library{}
headNodesList = list()
# Iterate dictionary and inner dictionary to add head nodes to headNodesList
for singerAlbums in self.musicLibraryDict.values():
for album in singerAlbums:
# Get head node (value) from dictionary
currHead = album[next(iter(album))]
# Add head node to list
headNodesList.append(currHead)
# Iterate headNodesList
newLinkList = LinkList()
for pos in range(0, len(headNodesList)):
# Merge 2 link lists and return a new one
newLinkList = self.mergeTwoSortedLinkList(newLinkList.getHead(), headNodesList[pos].getHead())
# Update final link list's head
self.finalMusicLinkList = newLinkList
def printMusicDictionary(self):
# OBJECTIVE: Print music library
# Iterate dictionary
print("Printing 'self.musicLibraryDict'")
for artistStr, albumsList in self.musicLibraryDict.items():
print("Artist: {}".format(artistStr))
# Iterate list
for albumDict in albumsList:
# Get key and value from dictionary
# NOTE: iter() => create an iterator
# next() => Go to next element within iterable
albumName = next(iter(albumDict))
albumNode = albumDict[albumName]
# Print link list
print("\tAlbum: {}".format(albumName))
print("\tSongs:")
while albumNode != None:
print("\t\t{}".format(albumNode.data))
albumNode = albumNode.next
print()
def addSongsToDictionary(self, albumNameStr, albumDirList, songsList, oldArtistAlbumsList):
# OBJECTIVE: Add an album and its songs as a dictionary to a list
# If sub_directory is empty and songs_list isn't, then we are inside an album directory
# We're currently in the location of the album's songs
if albumDirList == [] and songsList != []:
print("Preparing to add '{}' to 'oldArtistAlbumsList'".format(albumNameStr))
# Create a new link list of the album's songs
ll = LinkList()
# Add all songs inside directory to link list
for song in songsList:
ll.addNode(song)
# Sort link list
ll.head = ll.mergeSort(ll.getHead())
# ll.printForward()
# ll.printBackwards()
# Keep track of number of songs for self.finalMusicLibrary link list
self.totalSongs += ll.size
# Save album and songs as a dictionary to the list
# Ex. {album name: link list}
# oldArtistAlbumsList.append({albumNameStr: ll.getHead()})
oldArtistAlbumsList.append({albumNameStr: ll}) # NOTE: Save instance of LinkList
# print("Added '{}' with '{}' as head node to 'old_artist_albums'!".format(albumName, ll.getHead().data))
# Return album (list)
return oldArtistAlbumsList
def scanMusicDirectory(self):
# OBJECTIVE: Fetch all music inside the device from dedicated directory
# Get full path of Music folder
startingDir = "{}/Music".format(os.environ["HOME"])
print("Scanning device's Music directory")
# Hold name of directories last visited
oldArtistStr = ""
oldArtistAlbumsList = list()
while True:
# Get directories and files inside Music directory
# NOTE:
# 1. For-loop breakdown: string, list, list in os.walk(starting_dir)
# 2. "topdown=True" allows os.walk() to go to the bottom of the directory before going to any other
for directory, subDirectory, song in os.walk(startingDir, topdown=True):
# print("Directory: {}".format(directory))
# print("Subdirectory: {}".format(subDirectory))
# print("song: {}".format(song))
try:
# Split directory with "/" as denominator and slice it
directoryList = directory.split("/")[4:]
# Get album and song name from list
artist = directoryList[0]
album = directoryList[1]
# print("Artist: {}".format(artist))
# print("Album: {}".format(album))
except:
# print("Exception occurred!")
pass
else:
# If exception wasn't raised, execute code below
# If this is the 1st iteration, add artist to old_artist
if oldArtistStr == "":
# print("1st iteration, so I'll manually set 'old_artist' to 'artist'")
oldArtistStr = artist
# If old_artist == artist, then we haven't changed singers, so there must be more albums
if oldArtistStr == artist:
# print("'old_artist' and 'artist' match!")
oldArtistAlbumsList = self.addSongsToDictionary(album, subDirectory, song, oldArtistAlbumsList)
# If old_artist != artist, then we already have all the songs from "old_artist" and need to add a new "artist"
if oldArtistStr != artist:
# print("'old_artist' and 'artist' DON'T match!")
# Add old_artist with old_artist_albums to final dictionary
self.musicLibraryDict[oldArtistStr] = copy.deepcopy(oldArtistAlbumsList)
# Update variables
oldArtistStr = artist
oldArtistAlbumsList = []
oldArtistAlbumsList = self.addSongsToDictionary(album, subDirectory, song, oldArtistAlbumsList)
# print()
# Once for-loop ends, save last record of artist's songs and albums
# Add old_artist with old_artist_albums to final dictionary
self.musicLibraryDict[oldArtistStr] = copy.deepcopy(oldArtistAlbumsList)
# Exit while-loop
break
# self.printMusicDictionary()
def addMusicToDatabase(self):
# OBJECTIVE: Save all songs in directory to SQLite database
# Get full path of Music folder
startingDir = "{}/Music".format(os.environ["HOME"])
print("Scanning device's Music directory")
while True:
# Get directories and files inside Music directory
# NOTE:
# 1. For-loop breakdown: string, list, list in os.walk(starting_dir)
# 2. "topdown=True" allows os.walk() to go to the bottom of the directory before going to any other
for directory, subDirectory, songs in os.walk(startingDir, topdown=True):
try:
# Split directory with "/" as denominator and slice it
directoryList = directory.split("/")[4:]
# Get album and song name from list
artist = directoryList[0]
album = directoryList[1]
# print("Directory: {}".format(directory))
# print("Subdirectory: {}".format(subDirectory))
# print("Artist: {}".format(artist))
# print("Album: {}".format(album))
# print("Songs: {}".format(songs))
# print()
except:
# Skip to next iteration
continue
else:
# If exception wasn't raised, enter data to database
for song in songs:
# Define path name
# location = directory + "/" + song
# Insert new data to table
# NOTE: For 3rd argument, remove media file extension but keep it for file's pathname (location)
self.db.insert(artist, album, song[:-4], directory + "/" + song)
# Exit while-loop
break
# Outside of while-loop reorganize database and print table
self.db.reorganizeDatabase()
self.db.printTable()
def playWindow(self, songEntry):
# OBJECTIVE: A song's full pathname will be given. Play that song.
# Unpack argument variable
songName, songPath, songPos = songEntry[0], songEntry[1], songEntry[2]
# Initiate player
player = vlc.MediaPlayer(songPath)
player.play()
# Give playback options
isSongPlaying = True
while True:
print("\nNow Playing: {}".format(songName))
controls = input("f/r/p/b: ")
if controls == "f":
player.stop()
# Get another song based on positioning
songEntry = self.db.getSongByPos(songPos + 1)
songName, songPath, songPos = songEntry[0], songEntry[1], songEntry[2]
# Update player
player = vlc.MediaPlayer(songPath)
player.play()
elif controls == "r":
player.stop()
# Get another song based on positioning
songEntry = self.db.getSongByPos(songPos - 1)
songName, songPath, songPos = songEntry[0], songEntry[1], songEntry[2]
# Update player
player = vlc.MediaPlayer(songPath)
player.play()
elif controls == "p" and isSongPlaying == True:
player.pause()
isSongPlaying = False
elif controls == "p" and isSongPlaying == False:
player.play()
isSongPlaying = True
elif controls == "b":
break
def playSongFromDatabase(self):
# OBJECTIVE: When user clicks "songs", display all songs available in iPod
# Ask user to select song
while True:
# Display everything in "song" column of database
self.entryMsg("Music Library")
self.db.printSongsAvailable()
# Ask for what song to play
songSelected = input("Play: ")
# Play song from Nth row
songSelected = self.db.getSongByName(songSelected)
self.playWindow(songSelected)