Daily Develope

[Python] PCM 파일 통합 및 WAV로 변환 본문

Develope/Python

[Python] PCM 파일 통합 및 WAV로 변환

noggame 2022. 2. 15. 13:49

PCM 파일 통합(합치기)

: PCM은 파일의 시작에 소리 정보를 담고있는 header가 존재하지 않기 때문에, raw 데이터(Byte Code)를 그대로 읽어서 합치면된다.

targetList = ["{대상파일1_경로}", "{대상파일2_경로}"]
destinationPath = "{생성파일경로}"

buf = bytearray()
for file in targetList:
    f = open(file, 'rb')
    buf += f.read()
    f.close()

wf = open(destinationPath, 'wb')
wf.write(buf)
wf.close()

PCM 에서 WAV 로의 변환

: PCM 데이터를 WAV로 변환하려는 경우 WAV 파일이 어떻게 쓰였는지 나타내는 Header가 필요하다. Header에는 samplerate나 소리 데이터의 길이 등의 정보가 들어가며, 직접 구현하기보다는 numpy, librosa, soundfile 등의 라이브러리를 사용하면 간단히 해결 가능하다.

import numpy as np
import librosa as lr
import soundfile as sf

target = "{대상파일_경로}"
destinationPath = "{생성파일경로}"
buf = None

with open(target, 'rb') as tf:
    buf = tf.read()
    buf = buf+b'0' if len(buf)%2 else buf    # padding 0 (경우에 따라서 PCM 파일의 길이가 8bit[1byte]로 나누어 떨어지지 않는 경우가 있어 0으로 패딩값을 더해준다, 해당 처리를 하지 않는 경우 numpy나 librosa 라이브러리 사용 시 오류가 날 수 있다)

pcm_data = np.frombuffer(buf, dtype='int16')
wav_data = lr.util.buf_to_float(x=pcm_data, n_bytes=2)
sf.write(destinationPath, wav_data, 16000, format='WAV', endian='LITTLE', subtype='PCM_16')

WAV 에서 PCM 으로의 변환

: PCM과 WAV의 소리 데이터 부분은 동일하고, Header 부분만 차이가 나므로 WAV 파일에서 (Header를 제외한) 데이터 부분만 읽어서 파일로 만들면 PCM 파일에 해당한다.

target = "{대상파일_경로}"
destinationPath = target[:-4]+".pcm" # {생성파일경로}
buf = None

with open(destinationPath, "wb") as d_file:
    t_file = open(target, "rb")
    t_bin = t_file.read()
    d_file.write(t_bin[44:])    # header 이외의 데이터를 pcm 파일로 저장
    t_file.close()    
Comments