Python Forum
Looping through music files (SOLVED)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Looping through music files (SOLVED)
#1
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()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question [SOLVED] Right way to open files with different encodings? Winfried 3 9,517 Jan-18-2025, 02:19 PM
Last Post: Winfried
  [SOLVED] Loop through directories and files one level down? Winfried 3 4,117 Apr-28-2024, 02:31 PM
Last Post: Gribouillis
Question [solved] compressing files with python. SpongeB0B 1 1,672 May-26-2023, 03:33 PM
Last Post: SpongeB0B
  Help replacing word in Mutiple files. (SOLVED) mm309d 0 1,939 Mar-21-2023, 03:43 AM
Last Post: mm309d
  Delete empty text files [SOLVED] AlphaInc 5 4,391 Jul-09-2022, 02:15 PM
Last Post: DeaD_EyE
  Sorting and Merging text-files [SOLVED] AlphaInc 10 11,161 Aug-20-2021, 05:42 PM
Last Post: snippsat
  Replace String in multiple text-files [SOLVED] AlphaInc 5 12,657 Aug-08-2021, 04:59 PM
Last Post: Axel_Erfurt
  Looping through Folder structure and get files mfkzolo 0 2,606 Nov-02-2020, 08:31 AM
Last Post: mfkzolo
  How to concatenate files while looping through lists? python_newbie09 3 4,460 Mar-24-2019, 03:11 PM
Last Post: python_newbie09
  Looping through csv files in a folder WhatsupSmiley 3 11,262 Nov-13-2018, 08:39 PM
Last Post: Larz60+

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.