简体   繁体   English

如何在python3中将24位wav文件转换为16或32位文件

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

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 我正在尝试制作一堆.wav文件的谱图,以便我可以进一步分析它们(在python 3.6中),但是,我一直得到这个讨厌的错误

 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? 我已经研究了其他堆栈溢出帖子,例如如何在Python中编写24位WAV文件? but theses didn't solve the issue! 但论文没有解决问题!

I found a audio library called Pysoundfile 我找到了一个名为Pysoundfile的音频库

http://pysoundfile.readthedocs.io/en/0.9.0/ 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. 我查看了文档,我仍然不清楚如何将24位.wav文件转换为32位wav文件或16位wav文件,以便我可以从中创建谱图。

Any help would be appreciated! 任何帮助,将不胜感激!

I would suggest using SoX for this task. 我建议使用SoX来完成这项任务。 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. 如果你必须使用Python,那么你可以使用你发现的PySoundFile。 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. 您还应该使用soundfile.available_subtypes来查看可以将文件转换为哪些子类型。 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'}

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 我在BerkÖzbalcı的帮助下找到了解决方案我在下面写了一个函数来将.wav文件的目录转换为16位的wav文件

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM