简体   繁体   中英

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

I'm learning Python by making small games, with Turtle. I want a background music playing. It's the only sound that doesn't work. When I add this sound, other sounds don't work also !

Here is what I get :

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

My code:

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)

You should play the sound in another thread so that the code will be executing at the same time.

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)

I don't have experience with this module but hope you get the idea.

Just import playsound get the audio file you need and run it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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