Looping through music files (SOLVED) - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Looping through music files (SOLVED) (/thread-19769.html) |
Looping through music files (SOLVED) - ebolisa - Jul-13-2019 Hi, I just cannot understand why the below code is not looping. It plays a song and then stops and exits. TIA #!/usr/bin/python3 import random, os import pygame #music files path path = "/media/usb/" #get music files songs = os.listdir(path) #filter mp3 files songs = [fi for fi in songs if fi.endswith(".mp3") ] pygame.init() pygame.mixer.init() while True: try: #pygame.mixer.music.set_volume(0.50) filename = random.choice(songs) print('playing now {}'.format(filename)) pygame.mixer.music.load(path + filename) pygame.mixer.music.play() while pygame.mixer.music.get_busy(): pygame.time.Clock().tick(10) except ValueError: print('Excemption: {}', format(ValueError)) #if __name__ == '__main__':EDIT: Solved by moving lines around ;) #!/usr/bin/python3 import random, os import pygame #music files path path = "/media/usb/" #get music files songs = os.listdir(path) #filter mp3 files songs = [fi for fi in songs if fi.endswith(".mp3") ] pygame.init() pygame.mixer.init() #print(pygame.mixer.get_init()) def play_songs(): try: #pygame.mixer.music.set_volume(0.50) filename = random.choice(songs) #print('playing now {}'.format(filename)) pygame.mixer.music.load(path + filename) pygame.mixer.music.play() while pygame.mixer.music.get_busy(): pygame.time.Clock().tick(10) except ValueError: print('Excemption: {}', format(ValueError)) if __name__ == '__main__': while True: play_songs() |