簡體   English   中英

Python pygame.mixer不會無限播放音樂

[英]Python pygame.mixer does not play music infinitely

我想連續播放一個鬧鍾文件,直到它檢測到一個按鈕被按下為止。 在這種情況下,我使用鍵盤中斷來嘗試。

這是我的腳本:

import pygame

pygame.mixer.init()
pygame.mixer.music.load("beep.wav")
pygame.mixer.music.play(-1)
print "Time to take medicine!"

try:
    while pygame.mixer.music.get_busy() == True:
        continue

except KeyboardInterrupt:
    pygame.mixer.music.stop()

但是,它只播放一次,然后停止並退出腳本。 怎么了?

更新:我設法讓它運行並在鍵盤中斷時終止,但我不明白為什么play(-1)無法正常工作?

這是我的工作腳本:

import pygame
import sys

pygame.mixer.init()
pygame.mixer.music.load("beep.wav")
pygame.mixer.music.play(-1)
print "Time to take medicine!"

while True:
    try:
        while pygame.mixer.music.get_busy() == True:
            continue

    except KeyboardInterrupt:
        pygame.mixer.music.stop()
        sys.exit()

pygame手冊說關於

pygame.mixer.music.get_busy()

當音樂流正在播放時,返回True。 當音樂空閑時,它返回False。

因此,問題在於,當聲音結束並要重新開始時,此函數會在很小的間隙中返回False。 這就是您的第二個版本起作用的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM