如何在Python声音设备中录制特定时间的音频,直到一些动作(如键盘按压)



我对Python很陌生,所以我有一个小项目来了解更多关于Python的信息,我的项目很简单,只使用sounddevice录制音频,但问题是,在纪录片中,它只录制静态秒,就像下面的代码示例代码一样,我不知道如何停止或暂停录制,在我的情况下,只需按下一个键,比如"enter to stop,shift to pause">

import sounddevice as sd
import soundfile as sf
import time
def sync_record(filename, duration, fs, channels):
print('recording')
myrecording = sd.rec(int(duration * fs), samplerate=fs, channels=channels)
sd.wait()
sf.write(filename, myrecording, fs)
print('done recording')
# playback file
sync_record('sync_record.wav', 10, 16000, 1)

所以我的问题是,我如何在不需要持续时间的情况下暂停和录制音频,以及如何使用sounddevice停止和暂停,非常感谢大家

print "* record until keypress"
from openexp.keyboard import keyboard
# Short timeout so get_key() doesn't block
my_keyboard = keyboard(exp, timeout=2)
all = []
while my_keyboard.get_key()[0] == None: # Loop until a key has been pressed
data = stream.read(chunk) # Record data
all.append(data) # Add the data to a buffer (a list of chunks)
print "* done recording"

这说明了如何在按下某个键之前对数据进行流式传输。

import keyboard
k = keyboard.read_key()  # in my python interpreter, this captures "enter up"
k = keyboard.read_key()  # so repeat the line if in the python interpreter

对代码使用相同的逻辑。这样,一旦用户按下一个键,记录就会停止。

最新更新