You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

  1. Import required modules: Grab threading to create the background thread, plus playsound itself.
  2. Wrap audio playback in a function: This makes it easy to pass to the thread for background execution.
  3. 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 pygame or pyaudio—they have native non-blocking support. Here's a quick pygame example:
    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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 18:07:51