Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Use of pygame
#1
Hi,

The following code plays only the beginning of a file:

pygame.mixer.init()
pygame.mixer.music.load('my_music.mp3')
pygame.mixer.music.play()
pygame.mixer.music.set_volume(0.5)
If I add some delay say time.sleep(10), the file is played for 10 seconds. Why is that?

Also, once that is fixed, how can I stop the file from playing?

TIA
Reply
#2
Post pygame questions in the pygame forum.

Pygame programs have an event loop that keeps the program running. When the loop exists, the program ends. You have no loop so your program ends immediately, or after 10 seconds when you added the 10 second sleep. And when the program ends, the music ends.

If you want to wait until the song completes you'll need an event loop that processes the mixer event indicating the song is over.
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.USEREVENT:
            if not pygame.mixer.music.get_busy():  # Not sure this line is needed.
                running = False
And to have the mixer generate a USEREVENT when it reaches the end of the song add this to you startup code
pygame.mixer.music.set_endevent(pygame.USEREVENT)
Stopping music is up to you. Maybe you'll press a button, or maybe you'll type on the keyboard. The commands used to stop music playing are in mixer or mixer.music.

Use mixer to stop all sounds. Read about it here:
https://www.pygame.org/docs/ref/mixer.html

To just stop music, use mixer.music. Read about it here:
https://www.pygame.org/docs/ref/music.ht...ixer.music
Reply
#3
(Sep-30-2022, 06:27 PM)deanhystad Wrote: Post pygame questions in the pygame forum.

Pygame programs have an event loop that keeps the program running. When the loop exists, the program ends. You have no loop so your program ends immediately, or after 10 seconds when you added the 10 second sleep. And when the program ends, the music ends.

If you want to wait until the song completes you'll need an event loop that processes the mixer event indicating the song is over.

Thank you!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Pygame*import pygame ImportError: No module named pygame CASPERHANISCH 1 9,786 Jun-05-2017, 09:50 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020