EmileSteenkamp
EmileSteenkamp

Reputation: 31

pyaudio giving empty output file when recording sound [MacOS Mojave 10.14.6]

I want to make a recording from audio input and write to a wav file using pyaudio in python3. When running the code on our ubuntu lab computers it works, but when running it on my mac it writes no data to the file and I receive a silent wav file that is the correct duration.

import pyaudio
import wave

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "sound.wav"

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

print("* recording")

frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()

Upvotes: 2

Views: 590

Answers (1)

Reece Kenney
Reece Kenney

Reputation: 2964

My problem was that the app I was running the Python script didn't have microphone access (and it wasn't asking for access either). I was running the script from the terminal build in to VS Code.

The solution: Make sure the app you're running has microphone access. For me, I instead ran the script from the Terminal app and made sure it had microphone access:

enter image description here

Upvotes: 2

Related Questions