Playing mp3 with python tkinter and pygame
Just remove the while
loop from the stop
method:
def start(self):
path = str(self.ent.get())
mixer.init()
mixer.music.set_volume(0.2)
mixer.music.load(path)
mixer.music.play()
# DELETE
# while mixer.music.get_busy():
# time.Clock().tick(1)
This loop does not terminate while the music is playing and prevents the application from responding.
You only need such a loop in a native Pygame application to prevent the application from exiting immediately (see How can I play an mp3 with pygame? and how to play wav file in python?).
Is there a way to play multiple mp3 files at once in pygame?
Just so there's a formal answer to this question...
It's not possible to play multiple MP3
sound files simultaneously using channels with PyGame. They can be played singularly with the pygame.mixer.music
set of functions.
However, it's absolutely possible to convert your sound-files to OGG sound format - which is compressed much the same as MP3, or the uncompressed WAV format. Obviously this is not a solution if you want to write an MP3 music player, but for a game it's a minor a requirement. Free software such as Audacity is easily able to convert sound formats.
I have adapted the example from the comment link to not use the var
module. Like the linked code it continuously plays a rain-sound , and pressing h adds a car horn meep-meep into the output.
import pygame
# Window size
WINDOW_WIDTH = 400
WINDOW_HEIGHT = 400
WINDOW_SURFACE = pygame.HWSURFACE|pygame.DOUBLEBUF|pygame.RESIZABLE
DARK_BLUE = ( 3, 5, 54)
### initialisation
pygame.init()
pygame.mixer.init()
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ), WINDOW_SURFACE )
pygame.display.set_caption("Multi Sound")
### sound
# create separate Channel objects for simultaneous playback
channel1 = pygame.mixer.Channel(0) # argument must be int
channel2 = pygame.mixer.Channel(1)
# Rain sound from: https://www.freesoundslibrary.com/sound-of-rain-falling-mp3/ (CC BY 4.0)
rain_sound = pygame.mixer.Sound( 'rain-falling.ogg' )
channel1.play( rain_sound, -1 ) # loop the rain sound forever
# Car Horn sound from: https://www.freesoundslibrary.com/car-horn-sound-effect/ (CC BY 4.0)
horn_sound = pygame.mixer.Sound( 'car-horn.ogg' )
### Main Loop
clock = pygame.time.Clock()
done = False
while not done:
# Handle user-input
for event in pygame.event.get():
if ( event.type == pygame.QUIT ):
done = True
elif ( event.type == pygame.KEYUP ):
if ( event.key == pygame.K_h ):
if ( not channel2.get_busy() ): # play horn if not already playing
channel2.play( horn_sound )
print( 'meep-meep' )
# Window just stays blue
window.fill( DARK_BLUE )
pygame.display.flip()
# Clamp FPS
clock.tick_busy_loop(60)
pygame.quit()
How to play random Mp3 files in Pygame
First you have to get a list of all the files which ends with '.mp3'
in the directory (os.listdir
, see os):
import os
path = "C:/Users/pc/Desktop/sample_songs/"
all_mp3 = [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.mp3')]
then select a random file from the list (random.choice
, see random
):
import random
randomfile = random.choice(all_mp3)
Play the random file:
import pygame
pygame.mixer.init()
pygame.mixer.music.load(randomfile)
pygame.mixer.music.play()
Minimal example:
import os
import random
import pygame
directory = 'music'
play_list = [f for f in os.listdir(directory) if f.endswith('.mp3')]
print(play_list)
current_list = []
pygame.init()
window = pygame.display.set_mode((600, 100))
font = pygame.font.SysFont(None, 40)
clock = pygame.time.Clock()
window_center = window.get_rect().center
title_surf = None
run = True
while run:
clock.tick(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if not pygame.mixer.music.get_busy():
if not current_list:
current_list = play_list[:]
random.shuffle(current_list)
current_song = current_list.pop(0)
pygame.mixer.music.load(os.path.join(directory, current_song))
pygame.mixer.music.play()
title_surf = font.render(current_song, True, (255, 255, 0))
window.fill(0)
if title_surf:
window.blit(title_surf, title_surf.get_rect(center = window_center))
pygame.display.flip()
pygame.quit()
exit()
How can I play audio at the end of my python pygame project?
You have to wait for the music to finish playing:
win = pygame.mixer.Sound("sounds/win.mp3")
win.play()
while pygame.mixer.get_busy():
pygame.time.delay(10)
pygame.event.poll()
can't play mp3 files continuously inside a loop using pygame?
First time it play audio correctly but when it's recalled then it cant load mp3
After playing the music, the current working directory is changed in the function checknSetdir
, by os.chdir(target_path)
.
Get the current working directory at the begin of the application:
import os
currentWorkDir = os.getcwd()
Use an absolut path to load the file "Eyesound.mp3":
pygame.mixer.music.load(os.path.join(currentWorkDir, "Eyesound.mp3"))
How to play an mp3 file while a text based program is loading? Python
Following code works for me:
But it's almost no change to the code that you posted.
I'm running on linux with python 3.6 and pygame 1.9.6.
If it doesn't work, then please specify OS, python version and pygame version.
import pygame
import time
pygame.init()
pygame.mixer.music.load("elevmusic.mp3")
print("loaded")
pygame.mixer.music.play(loops=-1) # repeat indefinitely
print("started play")
print("Welcome user")
name = input("Client name: ")
gender = input("Mr or Miss: ")
age = input("Client age: ")
room = input("Room: ")
sure = input("""All done!!!
Press any key to show the view!""")
welcome = f"""Welcome to room {room} {gender}. {name}!
Have a nice stay"""
pygame.mixer.music.stop()
# pygame.mixer.music.fadeout(1000) # or use fadeout
if pygame.version.vernum >= (2, 0):
# free some resources. but this exists only for newer
# versions of pygame
pygame.mixer.music.unload()
if sure == "a":
print(welcome)
else:
print(welcome)
print("now simulating some activity without music")
time.sleep(10)
print("program ends")
Related Topics
Recursive Function Returning None in Python
How to Print a Date in a Regular Format
Adding Python to Path on Windows
Can't Pickle ≪Type 'Instancemethod'≫ When Using Multiprocessing Pool.Map()
Setting the Correct Encoding When Piping Stdout in Python
Django Csrf Check Failing With an Ajax Post Request
How to Send an Email With Gmail as Provider Using Python
Pandas: Filling Missing Values by Mean in Each Group
How to Define a Two-Dimensional Array
Why Is This Printing 'None' in the Output
Identify Groups of Continuous Numbers in a List
When Is "I += X" Different from "I = I + X" in Python
Does Python Optimize Tail Recursion