How can Python convert between wav and pcm files?
To convert between WAV and PCM formats, you can utilize Python’s wave library to handle audio files. The specific steps are as follows:
- Import the wave library.
import wave
- Open the wav file:
wav_file = wave.open('input.wav', 'rb')
- Read the parameters of the wav file.
nchannels = wav_file.getnchannels() # 通道数
sampwidth = wav_file.getsampwidth() # 采样宽度(字节)
framerate = wav_file.getframerate() # 采样率
nframes = wav_file.getnframes() # 音频帧数
- Accessing the audio data of a wav file:
frames = wav_file.readframes(nframes)
- Close the wav file.
wav_file.close()
- Open the PCM file:
pcm_file = wave.open('output.pcm', 'wb')
- Configure parameters for the PCM file.
pcm_file.setnchannels(nchannels) # 通道数
pcm_file.setsampwidth(sampwidth) # 采样宽度(字节)
pcm_file.setframerate(framerate) # 采样率
- Audio data written to PCM file:
pcm_file.writeframes(frames)
- Close the PCM file.
pcm_file.close()
By following the steps above, you can convert a WAV file to a PCM file. Please note that if you want to convert a PCM file to a WAV file, you just need to change the output file name in step 6 to WAV format.