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

使用playsound与multiprocessing时音频与计时器无法同步运行的问题

解决计时蜂鸣测试的同步问题

你的代码核心问题是创建进程时错误地直接执行了目标函数,导致音频播放和计时器无法同步启动,和if "begin beep test" in message:判断语句无关。

关键错误修正

在multitasking()函数中,你写了:

sound_process = multiprocessing.Process(target=beep_test())

这里的beep_test()是直接调用函数,程序会先完整播放音频,才会继续创建并启动进程,自然和计时器完全不同步。正确写法是传递函数对象本身(不带括号):

sound_process = multiprocessing.Process(target=beep_test)

额外优化点

用os.path.join规范路径拼接,避免手动拼接路径时的系统兼容性问题:

audio = os.path.join(cwd, "BTsound.mp3")

完整修正代码

import os
import playsound
import multiprocessing
import time

cwd = os.getcwd()

def beep_test():
    audio = os.path.join(cwd, "BTsound.mp3")
    playsound.playsound(audio, True)

def multitasking():
    sound_process = multiprocessing.Process(target=beep_test)
    sound_process.start()

    timer = 10

    while timer > 0 and sound_process.is_alive(): 
        time.sleep(1) 
        print(f"..{timer}") 
        timer -= 1

    if timer == 0: 
        sound_process.terminate()
        print("Time's up, runners must grab a water bottle and walk around. Do not sit down.")
    # 补充:处理音频提前结束的情况
    elif not sound_process.is_alive():
        print("Beep test audio finished before timer ended.")

if __name__ == "__main__":
    message = input("Type 'begin beep test' to launch the timed beep test.\n")
    if "begin beep test" in message:
        multitasking()

说明

  • 你提到的判断语句本身无问题,只要输入包含指定字符串就能触发功能,之前的同步问题完全由进程创建时的函数调用错误导致。
  • 测试时保持10秒计时器,生产环境改回600秒即可。
  • playsound 1.2.2版本的使用无需调整,符合你的需求。

内容的提问来源于stack exchange,提问作者Cassidy Mettraux

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 18:47:03