0

I'm trying to record some audio by using the sounddevice library in python. This is to create a sound-activated recording for a scanner.

I cannot use the record function as it requires a time specified which is not suitable for my program as each transmission may be of different length, so I added a callback to the stream and when the audio is above a certain level will trigger the recording by creating a new file and writing the buffer data to the wave file.

I have implemented the trigger successfully, however when I attempt to write to the file and open it, it is not what the transmission was, instead it is just corrupt static.

Here's my code:

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
furas
  • 134,197
  • 12
  • 106
  • 148
  • did you try to `close()` it ? Often system doesn't write directly but keep data in memory and write them when you use `close()` - and if you don't close it then it doesn't write it. – furas Jul 10 '21 at 14:36
  • Hi, I added f.close() to the code once the transmission ceased and the recording is still static only – Decoderstar Jul 11 '21 at 10:36

0 Answers0