python - 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 文件。
解决方案
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).
推荐阅读
- python - TensorFlow 路径性能安装
- amazon-web-services - AWS CloudEndure 迁移细节
- r - 当给出均值和方差时,R 中的 ANOVA 和 LSD 分组
- c# - Xamarin 表单 - Webview 检测 URL 更改
- php - 为什么ajax调用响应权限被拒绝
- amazon-web-services - 在 AWS Amplify 中设置不同的环境
- xss - Burp :从 document.location 读取数据并通过以下语句传递给 $()
- reactjs - 如何在反应中创建带有变体下拉列表的产品页面?
- c# - 如何使单击 ListBoxItem 内的按钮选择项目?
- ios - 在没有 XCode 的情况下从 Linux 使用 Flutter