Python Record Audio From Computer Speaker on Win 10 – Python Tutorial

By | February 22, 2022

Gennerally, we can record an audio from a microphone. However, if there is no any microphones in our computer, how can we record ? In this tutorial, we will introduce you how to record audio by speaker using python.

Enable stereo mix in win 10

In order to record audio using speaker, we should enable stereo mix in win 10 firstly.

Enable stereo mix in win 10 - step 1

You can click Manage sound devices. Then, you will see:

Enable stereo mix in win 10 - step 2

Click Enable button to enable stereo mix in win 10.

How to record audio by speaker in python?

We can use python sounddevice library to record.

First, we can install this package.

pip install sounddevice

Then, we can print all input and output devices for audio.

import sounddevice as sd

print(sd.query_devices())

Run this code, we will see:

input and output devices for audio in win 10

In order to record an audio, we should select an input device.

In this example, our record device is Realtek High Definition, which is the device when we enable stereo mix. The id = 2.

Select an input device to record

sd.default.device[0] = 2

We can use sd.default.device[0] to select an input device for sounddevice.

Finally, we can start to record an audio. Here is an example:

fs = 44100 # Hz
length = 30 # s
recording = sd.rec(frames=fs * length, samplerate=fs, blocking=True, channels=1)
sd.wait()
from scipy.io import wavfile
wavfile.write('pizza.wav', fs, recording)

In this example code, we will save a single channel audio, the sample rate is 44100, the time duration is 30 seconds. We also save this recorded file to pizza.wav.

Leave a Reply