如何在Python中播放背景音乐的同时执行其他功能?
How to Play Audio with playsound Without Blocking Your Script
Absolutely! The default behavior of playsound is blocking—it holds up your entire script until the audio finishes playing. To run your other functions and script logic while the music plays in the background, you can use Python's built-in threading module to handle audio playback in a separate thread.
Step-by-Step Solution
- Import required modules: Grab
threadingto create the background thread, plusplaysounditself. - Wrap audio playback in a function: This makes it easy to pass to the thread for background execution.
- Launch the thread: Start the audio function in a separate thread so your main script can keep running uninterrupted.
Full Code Example
import threading from playsound import playsound def play_background_audio(): # playsound runs in blocking mode here, but it's isolated to its own thread playsound("background_loop.mp3") # Create a thread targeting our audio playback function audio_thread = threading.Thread(target=play_background_audio) # Optional: Set daemon=True so the thread stops when your main script ends # Omit this if you want the music to finish even after the main script exits audio_thread.daemon = True # Start the thread (kicks off audio playback in the background) audio_thread.start() # Now run your other code—this executes alongside the music! print("Script is running while music plays in the background...") def my_custom_function(): print("Executing my custom function!") # Add your business logic here # Call your function while audio plays my_custom_function() # Optional: Wait for audio to finish before ending the script (remove daemon=True first) # audio_thread.join()
Extra Tips
- Loop the audio: To make the background music repeat, modify the playback function with a loop (add a stop condition if needed):
def play_background_audio(): while True: playsound("background_loop.mp3") # Add a condition here to break the loop (e.g., check a flag) - More control with alternative libraries: If you need to pause/stop audio mid-playback, consider
pygameorpyaudio—they have native non-blocking support. Here's a quickpygameexample:import pygame pygame.mixer.init() pygame.mixer.music.load("background_loop.mp3") pygame.mixer.music.play(-1) # -1 = loop indefinitely # Run your other code here print("Doing work while music loops...") # Stop the music later with: # pygame.mixer.music.stop()
内容的提问来源于stack exchange,提问作者gabriele tosti
相关产品推荐
相关产品推荐

