简体   繁体   English

如何使用 pygame 播放 mp3?

[英]How can I play an mp3 with pygame?

import pygame
file = 'some.mp3'
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load(file)
pygame.mixer.music.play()

This outputs, "Process finished with exit code 0", but it doesn't play anything.这会输出“进程已完成,退出代码为 0”,但它不播放任何内容。 How can I resolve this problem?我该如何解决这个问题?

The play function starts the music playing, but returns immediately. play 函数开始播放音乐,但立即返回。 Then your program reaches it's end, and the pygame object is automatically destroyed which causes the music to stop.然后你的程序就结束了,pygame 对象会自动销毁,这会导致音乐停止。

As you commented, it does play the music if you wait for it before exiting - because then the pygame object isn't destroyed until the while loop finishes.正如您所评论的,如果您在退出之前等待它,它确实会播放音乐 - 因为这样 pygame 对象在 while 循环完成之前不会被销毁。

while pygame.mixer.music.get_busy(): 
    pygame.time.Clock().tick(10)

The music stops because it's an asyncronous event, which means it'll keep going with the script.音乐停止是因为它是一个异步事件,这意味着它将继续与脚本一起播放。 then, the script stops instantly, not giving the music a chance to start.然后,脚本立即停止,不给音乐机会开始。 as stated before, you could use如前所述,您可以使用

while pygame.mixer.music.get_busy(): 
  pygame.time.Clock().tick(10)

however, even better is pygame.event.wait() , as it'll wait for all asynchronous events to end.然而,更好的是pygame.event.wait() ,因为它会等待所有异步事件结束。

Here is a super easy way.这是一个超级简单的方法。

import pygame
file = 'some.mp3'
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load(file)
pygame.mixer.music.play()
pygame.event.wait()

I've found a good solution from thepythongamebook.com :我从thepythongamebook.com找到了一个很好的解决方案:

pygame.mixer.pre_init(44100, -16, 2, 2048) # setup mixer to avoid sound lag

pygame.init()

pygame.mixer.init()

pygame.mixer.music.load('music_01.mp3')

pygame.mixer.music.play(-1)

try this one.试试这个。

import pygame

def pmusic(file):
    pygame.init()
    pygame.mixer.init()
    clock = pygame.time.Clock()
    pygame.mixer.music.load(file)
    pygame.mixer.music.play()
    while pygame.mixer.music.get_busy():
        print("Playing...")
        clock.tick(1000)

def stopmusic():
    pygame.mixer.music.stop()


def getmixerargs():
    pygame.mixer.init()
    freq, size, chan = pygame.mixer.get_init()
    return freq, size, chan


def initMixer():
    BUFFER = 3072  # audio buffer size, number of samples since pygame 1.8.
    FREQ, SIZE, CHAN = getmixerargs()
    pygame.mixer.init(FREQ, SIZE, CHAN, BUFFER)

try:
    initMixer()
    file = 'C:\\data\\03.mp3'
    pmusic(file)
except KeyboardInterrupt:  # to stop playing, press "ctrl-c"
    stopmusic()
    print("\nPlay Stopped by user")
except Exception:
    print("unknown error")

print("Done")

It seems the audio does not play because of the way you have imported it.由于您导入的方式,音频似乎无法播放。 The code below plays the sound as expected.下面的代码按预期播放声音。 Nothing has changed here except that rather than import pygame it uses from pygame import mixer .除了它使用from pygame import mixer import pygame而不是import pygame之外,这里没有任何变化。 This may be due to the fact Pygame is a package but I'm not sure.这可能是因为 Pygame 是一个包,但我不确定。

from pygame import mixer

file = 'some.mp3'
mixer.init()
mixer.music.load(file)
mixer.music.play()

PyGame has 2 different modules for playing sound and music, the pygame.mixer module and the pygame.mixer.music module. PyGame有 2 个不同的播放声音和音乐的模块, pygame.mixer模块和pygame.mixer.music模块。 This module contains classes for loading Sound objects and controlling playback.该模块包含用于加载 Sound 对象和控制播放的类。 The difference is explained in the documentation:文档中解释了差异:

The difference between the music playback and regular Sound playback is that the music is streamed, and never actually loaded all at once.音乐播放和常规声音播放之间的区别在于音乐是流式播放的,而不是一次真正加载。 The mixer system only supports a single music stream at once.混音器系统一次仅支持单个音乐流。

If you want to play a mp3 file, you need to initialize the module.如果要播放mp3文件,则需要对模块进行初始化。 Load the file with pygame.mixer.music.load .使用pygame.mixer.music.load加载文件。 Invoke pygame.mixer.music.play() to start playback of the music stream.调用pygame.mixer.music.play()开始播放音乐流。 Finally, you have to wait for the file to play.最后,您必须等待文件播放。
Use pygame.mixer.music.get_busy() to test if a sound is being mixed.使用pygame.mixer.music.get_busy()测试是否正在混合声音。 Query the status of the mixer continuously in a loop.循环不断地查询混音器的状态。
In the loop, you need to delay the time by either pygame.time.delay or pygame.time.Clock.tick .在循环中,您需要通过pygame.time.delaypygame.time.Clock.tick延迟时间。 In addition, you need to handle the events in the application loop.此外,您还需要处理应用程序循环中的事件。 See pygame.event.get() respectively pygame.event.pump() :分别参见pygame.event.get() pygame.event.pump()

For each frame of your game, you will need to make some sort of call to the event queue.对于游戏的每一帧,您都需要对事件队列进行某种调用。 This ensures your program can internally interact with the rest of the operating system.这确保您的程序可以在内部与操作系统的其余部分进行交互。

import pygame
pygame.init()

pygame.mixer.music.load('my_music.mp3')
pygame.mixer.music.play()

clock = pygame.time.Clock()
while pygame.mixer.music.get_busy():
    clock.tick(60)
    pygame.event.poll()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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