首页 > 解决方案 > Pygame 不抛出任何错误,但不播放任何音频

问题描述

我正在尝试使用 Pygame 播放 .mp3 或 .wav 文件。我想在运行 Raspbian Buster 的 Raspberry Pi 4 上执行此操作,尽管在 Windows 上进行了相同的测试并且出现了相同的结果:

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)

当我运行它时没有错误,以下输出到控制台:

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

我错过了一些明显的东西吗?我一直在使用 SimpleAudio 作为替代方案,但它只兼容 .wav 文件而不是 .mp3 文件。

标签: pythonaudiopygame

解决方案


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).


推荐阅读