简体   繁体   English

在 python 文件中播放录制的音频不起作用

[英]Playing recorded audio in a python file not working

I'm using sounddevice to record and play audio with python.我正在使用sounddevice用 python 录制和播放音频。 I'm using a very simple code which is running well from the python interpreter:我正在使用一个非常简单的代码,它在 python 解释器中运行良好:

import sounddevice as sd
from time import sleep

fs = 44100
myrec = sd.rec(int(fs*3), samplerate=fs, channels=2)
sleep(3)
sd.play(myrec, fs)

However, when I'm trying to run this code from a python file (or using PyCharm) it just won't play.但是,当我尝试从 python 文件(或使用 PyCharm)运行此代码时,它无法播放。 What is wrong with the code that's making it happen?实现它的代码有什么问题?

The problem is that sounddevice plays audio in background.问题是 sounddevice 在后台播放音频。 When the script ends, it won't wait for the playback to complete.当脚本结束时,它不会等待播放完成。 In Python interpreter, you stay in the session to listen, but from a script you need to wait for it explicitly:在 Python 解释器中,您留在会话中进行侦听,但是从脚本中您需要明确地等待它:

import sounddevice as sd
from time import sleep

fs = 44100
myrec = sd.rec(int(fs*3), samplerate=fs, channels=2)
sd.wait()
sd.play(myrec, fs)
sd.wait()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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