Record Sounds with Python and convert wav to mp3

To record with Python install scipy and sounddevice in cmd or powershell,

  • pip install sounddevice
  • pip install scipy

and then save a file (call it recording.py for example) and run it with the following code below here (using any editor):

import sounddevice as sd
from scipy.io.wavfile import write
import os

fs = 44100  # this is the frequency sampling; also: 4999, 64000
seconds = 5  # Duration of recording

myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2)
print("Starting: Speak now!")
sd.wait()  # Wait until recording is finished
print("finished")
write('output.wav', fs, myrecording)  # Save as WAV file
os.startfile("output.wav")

It will take some seconds to start recording, you will know when to start looking at the console on which it will be printed “Starting: Speak now”. There is no way to see on the screen when the time ends, for now.

This is a sample recorder with the code above. I used the microphone that I was using while I was recording, so it is possible to record from the microphone and save audio at the same time in the video file and the audio file.

Convert wav in mp3

Install pydub with pip install pydub and then save a file with this code

from pydub import AudioSegment
sound = AudioSegment.from_wav('output.wav')

sound.export('myfile.mp3', format='mp3')

 

Advertisement