试图用pythonsounddevice录制音频,但结果只是静态的

2024-04-25 18:13:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用python中的sounddevice库录制一些音频。这是为扫描仪创建声音激活录音

我不能使用record函数,因为它需要指定的时间,这不适合我的程序,因为每次传输的长度可能不同,因此我向流中添加了一个回调,当音频高于某个级别时,将通过创建新文件并将缓冲区数据写入wave文件来触发录制

我已经成功地实现了触发器,但是当我尝试写入文件并打开它时,它不是传输的内容,而是静态损坏

这是我的密码:

import time as timer
import wave

import numpy as np

import sounddevice as sd


RecordActivate = False
StartTime = 0


def print_sound(indata, outdata, frames, time, status):
    global RecordActivate
    global StartTime
    volume_norm = np.linalg.norm(indata) * 10
    VolumeLevel = int(volume_norm)
    global f
    if RecordActivate == False:
        print("itls false" + str(VolumeLevel))
        if VolumeLevel > 16:
            RecordActivate = True
            print("Begin")
            StartTime = timer.time()
            ThingTime = timer.strftime(
                "%Y-%m-%d %H:%M:%S", timer.localtime(timer.time())
            )
            print("Transmission detected at " + ThingTime)
            f = wave.open("scan.wav", "w")
            f.setnchannels(1)
            f.setsampwidth(1)
            f.setframerate(44100)

    if RecordActivate == True:
        if VolumeLevel < 16:
            print("Transmission ceased.")
            RecordActivate = False
        else:
            f.writeframes(indata.tobytes())
            print("recording..")


with sd.Stream(callback=print_sound):
    while True:
        thing = 0

Tags: 文件importfalsenormiftimeaswave