簡體   English   中英

為什么我不能在 Python 中使用背景音樂?

[英]Why can't I use a background music in Python?

我正在通過使用 Turtle 制作小游戲來學習 Python。 我要播放背景音樂。 這是唯一不起作用的聲音。 當我添加這個聲音時,其他聲音也不起作用!

這是我得到的:

winsound.PlaySound("background.wav", winsound.SND_ASYNC)
RuntimeError: Failed to play sound

我的代碼:

while True:
winsound.PlaySound("background.wav", winsound.SND_ASYNC)

wn.update()

# Move the ball
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)

您應該在另一個線程中播放聲音,以便代碼同時執行。

import time
import winsound
from threading import Thread

def play_sound():
   winsound.PlaySound("./background.wav", winsound.SND_FILENAME|winsound.SND_ASYNC)

while True:
   thread = Thread(target=play_sound)
   thread.start()
   print ('hello')
   time.sleep(2)

我沒有這個模塊的經驗,但希望你能明白。

只需import playsound獲取所需的音頻文件並運行它。

from playsound import playsound
playsound('audio.mp3') # The audio file you want to play.

暫無
暫無

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

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