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()