I'm trying to build a music player using pygame, but I'm facing a lot of problems.
The basic idea is to put some songs in a list and access them.
For shuffle option, I have imported random module and used randint method to generate random numbers which will be used as index values to access the list while the loop is true. The numbers are being generated as expected but
mixer.music.load(song_list[random_numbers)
is not working and no songs are playing.For the looping option, I have used a while loop that plays a particular song a certain number of times. I have written a code that is supposed to ask the user whether to continue listening or not when the loop breaks. Instead, this piece of code is being implemented before the loop breaks.
I have used if statements to implement shuffle and loop options. If both are false, the else statement will be executed and the songs are supposed to play in sequential order. For this, I have used a 'for' loop to iterate over the song list, but 'for' loop is not working the loop breaks without even being executed
# playlist using python
def dir_path(path):
try:
import os
import time
import random
from pygame import mixer
mixer.init()
# songs list
songs_list = []
lis = os.listdir(path)
for i in lis:
a = os.path.join(path, i)
songs_list.append(a)
# to enable shuffling
shuffle = input('enable shuffling? y/n: ')
if shuffle.lower() == 'y':
b = []
t_end = time.time() + 60 * float(input('play time in minutes: '))
while time.time() < t_end:
a = random.randint(0, len(songs_list) - 1)
if a not in b:
b.append(a)
mixer.music.load(songs_list[a])
mixer.music.play()
if len(b) == len(songs_list):
b.clear()
print('thanks for listening :)')
# to enable looping
elif shuffle.lower() == 'n':
loop = input('enable looping? y/n: ')
if loop.lower() == 'y':
sl_num = 1
for i in lis:
print(f'{sl_num}) {i}')
sl_num += 1
sl_no = int(input('sl_no of the song: '))
loop_no = int(input('number of loops: '))
loop_times = 0
while loop_times < loop_no:
if sl_no <= len(songs_list):
mixer.music.load(songs_list[sl_no - 1])
mixer.music.play()
loop_times += 1
else:
print(f'only {len(songs_list)} songs are available')
loop_times = loop_no
if loop_times == loop_no:
conn = input('continue listening? y/n: ')
if conn.lower() == 'y':
dir_path(path)
elif conn.lower() == 'n':
print('Thanks for listening :)')
break
else:
print('invalid command')
break
# to play songs in order
elif loop.lower() == 'n':
for i in range(0, len(songs_list)):
mixer.music.load(songs_list[i])
mixer.music.play()
print('thanks for listening :)')
else:
print('invalid command')
else:
print('invalid command')
except KeyboardInterrupt:
print('Thanks for listening :)')
dir_path('song directory path')