Skip to content

Instantly share code, notes, and snippets.

@tsonglew
Created June 1, 2021 06:11
Show Gist options
  • Save tsonglew/83d8f18c54f698282c54de38f08b3fcd to your computer and use it in GitHub Desktop.
Save tsonglew/83d8f18c54f698282c54de38f08b3fcd to your computer and use it in GitHub Desktop.
pcm2wav and wav2pcm
import numpy as np
import wave
def wav2pcm(wavfile, pcmfile, data_type=np.int16):
f = open(wavfile, "rb")
f.seek(0)
f.read(44)
data = np.fromfile(f, dtype= data_type)
data.tofile(pcmfile)
def pcm2wav(pcm_file, wav_file, channels=1, bits=16, sample_rate=16000):
pcmf = open(pcm_file, 'rb')
pcmdata = pcmf.read()
pcmf.close()
if bits % 8 != 0:
raise ValueError("bits % 8 must == 0. now bits:" + str(bits))
wavfile = wave.open(wav_file, 'wb')
wavfile.setnchannels(channels)
wavfile.setsampwidth(bits // 8)
wavfile.setframerate(sample_rate)
wavfile.writeframes(pcmdata)
wavfile.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment