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

14,535

Solution 1

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'}

Solution 2

I found the solution with the help of Berk Özbalcı I wrote a function below to convert a directory of .wav files to 16-bit wav files

def convertAllFilesInDirectoryTo16Bit(directory):
    for file in os.listdir(directory):
         if(file.endswith('.wav')):
             nameSolo = file.rsplit('.', 1)[0]
             print(directory + nameSolo )
             data, samplerate = soundfile.read(directory + file)                

           soundfile.write('/Users/yournamehere/Desktop/folderwhereyouwanttosae/' + nameSolo + '16BIT.wav', data, samplerate, subtype='PCM_16')
            print("converting " + file + "to 16 - bit")
Share:
14,535
Sreehari R
Author by

Sreehari R

Updated on June 12, 2022

Comments

  • Sreehari R
    Sreehari R almost 2 years

    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!

  • Sreehari R
    Sreehari R almost 7 years
    Thanks a lot for your help!
  • Sreehari R
    Sreehari R almost 7 years
    When I run data, samplerate = soundfile.read('dog_bark.wav') I get a runtime error. It says Error opening 'dog_bark.wav'': System error.
  • Berk Özbalcı
    Berk Özbalcı almost 7 years
    Are you running the script in the same directory as the audio file?
  • Sreehari R
    Sreehari R almost 7 years
    It works now. I'll post my final code below to help anyone who faces the same issue!
  • Admin
    Admin over 4 years
    I get this error, "RuntimeError: Error opening 'audio.wav': File contains data in an unknown format."