python pcm转wav,如何将.pcm文件转换为.wav文件(脚本)

I would like to convert .pcm files to .wav files using a tool such as SOX in a Python script. The tool needs to be cross platform compatible (Windows & Linux). Any suggestions?

解决方案

You dont actually need a tool for this. The Python standard library comes with the wave module for writing .wav files, and of course raw .pcm files can be just opened as plain binary files, and if you need to do any simple transformations that arent trivial with a list comprehension, theyre trivial with audioop.

For example, this is a complete program from converting stereo 16-bit little-endian 44.1k PCM files to WAV files:

import sys

import wave

for arg in sys.argv[1:]:

with open(arg, rb) as pcmfile:

pcmdata = pcmfile.read()

with wave.open(arg+.wav, wb) as wavfile:

wavfile.setparams((2, 2, 44100, 0, NONE, NONE))

wavfile.writeframes(pcmdata)

In older versions of Python, you may have to use with contextlib.closing(wave.open(…)) (or an explicit open and close instead of a with statement).

I would like to convert .pcm files to .wav files using a tool such as SOX in a Python script. The tool needs to be cross platform compatible (Windows & Linux). Any suggestions? 解决方案 You dont actually need a tool for this. The Python standard library comes with the wave module for writing .wav files, and of course raw .pcm files can be just opened as plain binary files, and if you need to do any simple transformations that arent trivial with a list comprehension, theyre trivial with audioop. For example, this is a complete program from converting stereo 16-bit little-endian 44.1k PCM files to WAV files: import sys import wave for arg in sys.argv[1:]: with open(arg, rb) as pcmfile: pcmdata = pcmfile.read() with wave.open(arg+.wav, wb) as wavfile: wavfile.setparams((2, 2, 44100, 0, NONE, NONE)) wavfile.writeframes(pcmdata) In older versions of Python, you may have to use with contextlib.closing(wave.open(…)) (or an explicit open and close instead of a with statement).
经验分享 程序员 微信小程序 职场和发展