python - 现场录音延迟
问题描述
我是使用 python 进行音频处理的菜鸟。我从互联网上获得了以下 python 代码来执行实时录音。每当我使用以下代码进行录制时,录制的音频文件的开头都会有一个零块。录制不会立即开始,它会在录制开始之前添加零。
我希望录制立即发生,我在开始时运行没有任何零的代码。任何帮助表示赞赏。
import argparse
import tempfile
import queue
import sys
def int_or_str(text):
"""Helper function for argument parsing."""
try:
return int(text)
except ValueError:
return text
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'-l', '--list-devices', action='store_true',
help='show list of audio devices and exit')
parser.add_argument(
'-d', '--device', type=int_or_str,
help='input device (numeric ID or substring)')
parser.add_argument(
'-r', '--samplerate', type=int, help='sampling rate')
parser.add_argument(
'-c', '--channels', type=int, default=1, help='number of input channels')
parser.add_argument(
'filename', nargs='?', metavar='FILENAME',
help='audio file to store recording to')
parser.add_argument(
'-t', '--subtype', type=str, help='sound file subtype (e.g. "PCM_24")')
args = parser.parse_args()
try:
import sounddevice as sd
import soundfile as sf
import numpy # Make sure NumPy is loaded before it is used in the callback
assert numpy # avoid "imported but unused" message (W0611)
if args.list_devices:
print(sd.query_devices())
parser.exit(0)
if args.samplerate is None:
device_info = sd.query_devices(args.device, 'input')
# soundfile expects an int, sounddevice provides a float:
args.samplerate = int(device_info['default_samplerate'])
if args.filename is None:
args.filename = tempfile.mktemp(prefix='delme_rec_unlimited_',
suffix='.wav', dir='')
q = queue.Queue()
def callback(indata, frames, time, status):
"""This is called (from a separate thread) for each audio block."""
if status:
print(status, file=sys.stderr)
q.put(indata.copy())
# Make sure the file is opened before recording anything:
with sf.SoundFile(args.filename, mode='x', samplerate=args.samplerate,
channels=args.channels, subtype=args.subtype) as file:
with sd.InputStream(samplerate=args.samplerate, device=args.device,
channels=args.channels, callback=callback):
print('#' * 80)
print('press Ctrl+C to stop the recording')
print('#' * 80)
while True:
file.write(q.get())
except KeyboardInterrupt:
print('\nRecording finished: ' + repr(args.filename))
parser.exit(0)
except Exception as e:
parser.exit(type(e).__name__ + ': ' + str(e))
解决方案
推荐阅读
- python - Docx 不会替换从 pandas 中提取的文本
- swift - 在子视图中更新 ObservableObject 的 @Published 变量
- python - 使用 OpenCV 将 RGB 图像转换为灰度图像时,为什么会得到绿色图像?
- sql - 将表从 Oracle 迁移到 SQL Server
- vba - 与 sumif 类似的连接代码
- python - 为什么我的 Python 和 pip 在不同的地方?
- java - SimpleJdbcCall Oracle 存储过程错误的参数数量或类型
- python - csv 列/未知数据中的连字符导致 int 转换错误
- typescript - 如何等待多个可观察流解决并一起返回它们
- python - 如何在运行时撤销任务