gpt4 book ai didi

python - mp3 音频从交互式 python 播放,但不是从 bash 播放

转载 作者:行者123 更新时间:2023-12-01 04:56:44 29 4
gpt4 key购买 nike

我正在使用 pygame 模块在 python 中操作声音文件。它在交互式 python session 中工作正常,但相同的代码在 bash 中不会产生任何结果:

交互式Python

$ sudo python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> from pygame import mixer
>>> mixer.init()
>>> mixer.music.load('zho1ngguo2.mp3')
>>> mixer.music.play()

==>声音播放

但是 bash 没有发生任何事情:

$ cat  playmp3.py
import pygame
from pygame import mixer
mixer.init()
mixer.music.load('zho1ngguo2.mp3')
mixer.music.play()

$ sudo python playmp3.py

==>没有声音

有什么想法吗?

最佳答案

mixer.music.play() 仅开始播放,它不会阻止 python 立即退出(从而结束播放)。你必须等到歌曲结束。最直接的方法是告诉 mixer.music 在播放结束时向您发送一个事件并等待它:

import pygame
from pygame import mixer

# to use the event queue, this is required.
pygame.init()

mixer.init()

# or some other event id. This just has to be the same here and below.
mixer.music.set_endevent(pygame.USEREVENT + 1)
mixer.music.load('foo.mp3')
mixer.music.play()

ev = 0

while ev != pygame.USEREVENT + 1:
ev = pygame.event.wait()

关于python - mp3 音频从交互式 python 播放,但不是从 bash 播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27202997/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com