抓屏截图后pygame无法播放mp3

时间:2020-03-28 11:04:25

标签: python python-3.x pygame

我有一些代码可以让PyGame播放mp3。但是抓取屏幕截图后我无法播放mp3

file_A.py

from pygame import mixer
mixer.init()
def play(PATH, target):

    # play the sound
    print("play", target + ".mp3")
    mixer.music.load(PATH + target + ".mp3")
    mixer.music.play()

play("x","y")                   // its work if i call here

file_B.py

from .file_A import play
import pyscreenshot as ImageGrab

def main():

    play("x1","y")                           // its working here, but
    left = ImageGrab.grab(bbox=(1,2,3,4))    // after grab
    play("x2","y")                           // log printed that method called but sound not working

python 3.7.4 pygame 1.9.6 pyscreenshot 1.0.0

2 个答案:

答案 0 :(得分:1)

假设文件位于同一目录中,我唯一的假设可能是,当将该函数导入另一个文件时,它可能会遇到路径问题,因此可能无法播放该文件。

对于您的路径称为"xy.mp3",我也感到困惑。 您可以尝试为其提供绝对路径,例如

将函数定义更改为以下内容,然后尝试从file_B.py调用它

def play():

    # play the sound
    print("play", target + ".mp3")
    mixer.music.load("c:/programs/mygame/music/8bit-jingle-twist.mp3")
    mixer.music.play()

另外,请考虑在播放功能中添加此行pygame.mixer.music.stop(),以确保在获取下一个实例播放实例之前正确终止正在使用的音乐频道。

答案 1 :(得分:0)

我发现了主要问题,它不是bug。但是音频中断会压缩该方法中已经执行的所有代码,并且在混音器播放音频之前完成该方法

file_B.py

from .file_A import play
import pyscreenshot as ImageGrab
import time

def main():

    play("x1","y")                           // its working here, but
    left = ImageGrab.grab(bbox=(1,2,3,4))    // after grab
    play("x2","y")                           // log printed that method called but sound not working
    time.sleep(n)                            // wait the audio play

在混音器播放之后

将其添加到file_a.py上

while mixer.music.get_busy(): 
        time.Clock().tick(10)
相关问题