简体   繁体   中英

Pygame throws no errors but doesn't play any audio

I am trying to use Pygame to play an .mp3 or .wav file. I want to do this on my Raspberry Pi 4 running Raspbian Buster, although the same test has been made on Windows and the same results occur:

import pygame

pygame.init()
pygame.mixer.init()


audioFiles = [r'C:\pythonAudio\romeo&juliet.wav']

pygame.mixer.music.load(audioFiles[0])
pygame.mixer.music.play(0)

No errors are thown when I run this and the following is output to the console:

pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
[Finished in 1.372s]

Am I missing something obvious? I have been using SimpleAudio as an alternative which works but is only compatible with .wav files as opposed to .mp3.

The program ends as the music is being played in a different thread. In other words, pygame.mixer.music.play(0) will not wait for your song to finish but instead play it simultaneously with your program. Try:

import pygame

pygame.init()
pygame.mixer.init()


audioFiles = [r'C:\pythonAudio\romeo&juliet.wav']

pygame.mixer.music.load(audioFiles[0])
pygame.mixer.music.play(0)

while pygame.mixer.music.get_busy():
    pygame.event.pump()

This will keep your program running until the mixer is no longer busy (no longer playing any music).

Try converting it to an Ogg. Support for the other audio formats tends to be a bit inconsistent with Pygame.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM