Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a 24-bit wav file to 16 or 32 bit files in python3

Tags:

python

audio

wav

I am trying to make spectrogram's of a bunch of .wav files so I can further analyze them(in python 3.6), however, I keep getting this nasty error

 ValueError: Unsupported bit depth: the wav file has 24-bit data.

I have looked into other stack overflow posts such as How do I write a 24-bit WAV file in Python? but theses didn't solve the issue!

I found a audio library called Pysoundfile

http://pysoundfile.readthedocs.io/en/0.9.0/

I installed it with

pip3 install pysoundfile

I have looked over the documentation and it is still not clear to me how to convert a 24-bit .wav file to a 32-bit wav file or a 16-bit wav file so that I can create a spectrogram from it.

Any help would be appreciated!

like image 850
Sreehari R Avatar asked Jun 28 '17 21:06

Sreehari R


People also ask

Which is better WAV 16 bit or 32 bit?

The only real difference between 16, 24 and 32 bit audio is the dynamic range. A 16, 24, or 32 bit audio file will not capture any “extra” frequencies or produce something that sounds more “3D”. Bit depth just determines the noise floor of the audio file.

How do I change the bit rate of a WAV file in Windows?

Hit the gear icon right next to the audio file. Select the Audio section and choose WAV. Click on Settings again and choose the new bitrate for your WAV file. Click on Create to finalize the settings made.

Can a WAV file be 24 bit?

File Format: 24-bit/44.1k Sample Rate (or higher) WAV Files. Files uploaded to Bandcamp and SoundCloud can be 24-bit, and at higher sampler rates than 44.1k if available from the mastering engineer, which could make for better sound quality on the resulting data-compressed files such as mp3s.


1 Answers

I would suggest using SoX for this task. Changing the bit depth is very simple:

sox old.wav -b 16 new.wav

If you must use Python, then you could use PySoundFile as you found. Here's a little code snippet:

import soundfile

data, samplerate = soundfile.read('old.wav')
soundfile.write('new.wav', data, samplerate, subtype='PCM_16')

You should also use soundfile.available_subtypes to see which subtypes you can convert a file to. Here's its sample usage, taken from their documentation:

>>> import soundfile as sf
>>> sf.available_subtypes('FLAC')
{'PCM_24': 'Signed 24 bit PCM',
 'PCM_16': 'Signed 16 bit PCM',
 'PCM_S8': 'Signed 8 bit PCM'}
like image 129
Berk Özbalcı Avatar answered Oct 15 '22 12:10

Berk Özbalcı