python - 如何在所有操作系统中使用 pygame 播放声音?

标签 python windows ubuntu pygame

我写了一个 python 脚本来播放声音。

#!/usr/bin/python

import pygame
import time
def playNotificationSount():
    pygame.init()
    pygame.mixer.music.load("notification.mp3")
    pygame.mixer.music.play()
    time.sleep(10)
playNotificationSount()

它可以在 ubuntu 中播放声音,但在 windows 中没有声音。它没有给出错误信息。
如何改进脚本以便它可以在所有操作系统中播放声音?

最佳答案

如果你想在不打开 pygame 窗口的情况下播放声音(或音乐),你必须调用 pygame.mixer.init() 在您调用 pygame.init() 之前(或仅调用 pygame.mixer.init() )。我不清楚你必须这样做的原因,但它确实有效。这是一个最小的例子:

import pygame


pygame.mixer.init()  # Initialize the mixer module.
sound1 = pygame.mixer.Sound('notification.mp3')  # Load a sound.

while True:
    inpt = input('Press enter to play the sound: ')
    sound1.play()  # Play the sound.
    print('Playing sound')

在正常游戏中,您必须调用 pygame.display.set_mode()在播放音乐或声音之前打开一个 pygame 窗口,您不必调用 pygame.mixer.init()分别地。另外,调用pygame.mixer.pre_init(44100, -16, 2, 2048)之前 pygame.init()如果声音有问题,可以提供帮助。
import pygame


pygame.mixer.pre_init(44100, -16, 2, 2048)
pygame.init()
screen = pygame.display.set_mode((640, 480))

def playNotificationSound():
    pygame.mixer.music.load('notification.mp3')
    pygame.mixer.music.play()

playNotificationSound()

关于python - 如何在所有操作系统中使用 pygame 播放声音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43758408/

相关文章:

python - 访问 Python Azure Function 中的绑定(bind)表达式值

python - 从数据库重新加载 django 对象

windows - 如何在window中运行libsvm的easy.py?

windows - 创建一个 python 脚本来编译和运行一个 c++ 文件

python - 如何获得插入计算机的可移动驱动器列表?

ruby - "in ` 需要 ': cannot load such file -- iconv (LoadError)"

python - Numpy根据XYZ获取最大值

python - tensorflow : Update Certain Tensor Indices On a Condition

ubuntu - 在 Ubuntu 14.04 上运行 ZooInspector

ubuntu - 如何从 GO 语言的程序中给出 ubuntu 终端命令?