1

I found some code online that is supposed to record audio using soundfile but after creating the recording, when I play it back, I can't hear anything. However, the recording is the correct duration, I think it just isn't receiving input.

import sounddevice as sd
import soundfile as sf
import threading
import queue


class AudioRecorder:
    def __init__(self):

        self.open = True
        self.file_name = None
        self.channels = 1
        self.q = queue.Queue()

        device_info = sd.query_devices(2, 'input')
        self.samplerate = int(device_info['default_samplerate'])

    def callback(self, indata, frames, time, status):
        self.q.put(indata.copy())

    def record(self):
        with sf.SoundFile(self.file_name, mode='x', samplerate=self.samplerate, channels=self.channels) as file:
            with sd.InputStream(samplerate=self.samplerate, channels=self.channels, callback=self.callback):
                while self.open is True:
                    file.write(self.q.get())

    def stop(self):
        self.open = False

    def start(self, file_name):
        self.open = True
        self.file_name = file_name

        audio_thread = threading.Thread(target=self.record)
        audio_thread.start()


recorder = AudioRecorder()
recorder.start('recording.wav')
input('')
recorder.stop()

Original code: https://github.com/kpolley/Python_AVrecorder/

Does anyone know what's happening? Does if have something to do with getting the wrong input device? I'm new to audio in python.

I also tried this:

from threading import Thread
import pyaudio
import wave

def record():
    global stream, close, frames
    while True:
        if close: break
        data = stream.read(1024)
        frames.append(data)


audio = pyaudio.PyAudio()
close = False
stream = audio.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True, frames_per_buffer=1024)
frames = []

Thread(target=record).start()
input('')
close = True

stream.stop_stream()
stream.close()
audio.terminate()

sound_file = wave.open("recording.wav", "wb")
sound_file.setnchannels(1)
sound_file.setsampwidth(audio.get_sample_size(pyaudio.paInt16))
sound_file.setframerate(44100)
sound_file.writeframes(b''.join(frames))
sound_file.close()
Walker
  • 121
  • 1
  • 9
  • your code works well, one way you can try is to run the command `python3 -m sounddevice` and will return devices , for example for me it returned `> 0 Built-in Microphone, Core Audio (2 in, 0 out) < 1 Built-in Output, Core Audio (0 in, 2 out)` , so for me this line `device_info = sd.query_devices(2, 'input')` will be `device_info = sd.query_devices(0, 'input')` , if this does not debug, pls try to check the microphone too. – simpleApp Mar 26 '23 at 16:39
  • I tried switching to reltek which is input 1 but It still hasn't worked. I also tried something else, check the question again. – Walker Mar 26 '23 at 16:42

0 Answers0