Tuesday, March 8, 2022

Python - How to use Soundfile to read and write WAV and FLAC files

WAV and FLAC are two commonly used sound file formats:

WAV - Waveform Audio File Format (Wikipedia)

FLAC - Free Lossless Audio Codec (Wikipedia)

The major difference between the two formats is that WAV is without compression and FLAC is for lossess compression.

In Python, to read and write WAV and FLAC files including export in a different format, simply use the code with Soundfile as below:

import soundfile as sf

with open('wav/1.wav', 'rb') as f_wav:

    x_wav, rate = sf.read(f_wav)

with open('flac/2.flac', 'rb') as f_flac:

    x_flac, rate = sf.read(f_flac)

#exchange sound formats by saving

sf.write('1.flac', x_wav, 16000)

sf.write('2.wav', x_flac, 16000)

No comments:

Post a Comment