[Tkinter] Button Plays Random .MP3 File From Folder - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: GUI (https://python-forum.io/forum-10.html) +--- Thread: [Tkinter] Button Plays Random .MP3 File From Folder (/thread-32357.html) |
Button Plays Random .MP3 File From Folder - blufacebaby - Feb-05-2021 I have been trying to figure this out for a while, and can't find a solution to why it won't work. I'm pretty new, and this is probably an easy fix, but this code: from tkinter import * import pygame import os import random root = Tk() root.title('Hello') root.geometry('500x400') pygame.init() pygame.mixer.init() randomfile = random.choice(os.listdir("D:/Desktop/Plugin")) def play(): pygame.mixer.music.load(randomfile) pygame.mixer.music.play(loop=0) startButton = Button(root, text="Start", font=("Helvetica", 32), command=play) startButton.pack(pady=20) def stop(): pygame.mixer.music.stop() stopButton = Button(root, text="Stop", command=stop) stopButton.pack(pady=20) root.mainloop()Will always give me the error: pygame.error: Couldn't open 'audio2.mp3' I have 3 audio files in the folder and can't figure out why this wouldnt work. RE: Button Plays Random .MP3 File From Folder - deanhystad - Feb-05-2021 You are getting the name of a file in folder D:/Desktop/Plugin. To open the file you need to specify the filename and folder RE: Button Plays Random .MP3 File From Folder - BashBedlam - Feb-05-2021 You will need to give pygame mixer the full path to the file. Something like this : randomfile = random.choice(os.listdir("D:/Desktop/Plugin")) full_file_name = 'D:/Desktop/Plugin/' + randomfile pygame.mixer.music.load (full_file_name)Also loop=0 is not valid. The correct syntax is :pygame.mixer.music.play(0)This worked great on my system : from tkinter import * import pygame import os import random root = Tk() root.title('Hello') root.geometry('500x400') pygame.init() pygame.mixer.init() path = '/home/BashBedlam/test/' randomfile = random.choice(os.listdir("test")) filename = path + randomfile def play(): pygame.mixer.music.load(filename) pygame.mixer.music.play(0) startButton = Button(root, text="Start", font=("Helvetica", 32), command=play) startButton.pack(pady=20) def stop(): pygame.mixer.music.stop() stopButton = Button(root, text="Stop", command=stop) stopButton.pack(pady=20) root.mainloop() |