[파이썬, Python] Wave 파일을 PCM 파일로 바꿔 저장하는 예제 4.


예제 3에서 약간 변경해서, stereo wav 파일일 경우에, left channel만 취해서 pcm 파일로 만드는 예제로 변경해 보았습니다.


#!/usr/bin/python

import sys

import os.path


ext = None


def convert_wave_to_pcm(filename):

file = open(filename, 'rb')

byteBuffer = bytearray(file.read())

file.close()


fn_ext = os.path.splitext(filename)

if fn_ext[1] == '.wav':

out_filename = fn_ext[0] + '.pcm'

else:

out_filename = fn_ext[0] + fn_ext[1] + '.pcm'

print 'Out file name: %s' % out_filename

out_file = open(out_filename, 'wb')

for x in range(44, byteBuffer.len(),4):

out_file.write(byteBuffer[x:x+1])

out_file.close()


if len(sys.argv) is 1:

YesNo = raw_input('Do you want to convert *.wav to *.pcm? (Yes or No): ') # There is no option.

if 'yes' in YesNo:

filename = '.wav'

print('Convert *.wav to *.pcm !!!')

else:

print('Please try it again with a filename or .wav !!!')

exit(0)

else:

filename = sys.argv[1]


while True:

fn_ext = os.path.splitext(filename)

if (not fn_ext[1]) & fn_ext[0].count('.'):

if fn_ext[0] == '.':

print 'Input file name is invalid!!!'

exit(0)

else:

print 'Input file name has the only ext!!!'

ext = fn_ext[0]

break

else:

try:

convert_wave_to_pcm(filename)

break

except:

print '[Error] No such file: %s' % filename

filename = raw_input('Please type file name: ')


if ext is not None:

folder = os.getcwd()

print 'folder: %s' % folder

for path, dirs, files in os.walk(folder):

convert_wave_to_pcm(os.path.join(path, filename)) for filename in files if filename.endswith(ext)


raw_input('Press Enter to exit')

exit(0)



wave2pcm_stereo2mono.py




[내 블로그 관련글]


반응형

+ Recent posts