[파이썬, 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




[내 블로그 관련글]


반응형


[파이썬, python] 한글 (UTF-8) 지원하기


파이썬에서 한글(UTF8) 때문에 문제가 발생한다면 아래와 코드를 추가해보세요.


#-*- coding: utf-8 -*-


import sys


reload(sys)

sys.setdefaultencoding('utf-8')




반응형


[파이썬, python] 바이너리 파일 만들기


파이썬으로 바이너리 파일을 만드는 간단한 예제입니다. 

2byte little-endian 형식으로 1, 0, -1, 0을 40000번 판복해서 저장하기 위한 예제입니다. 

(amplitude가 1인 삼각파형 오디오 파일 만드는 예제입니다.)


import os.path


byteBuffer = bytearray([1,0,0,0,255,255,0,0])


out_file = open('binaryfile.dat', 'wb')

for x in range(0,40000):

out_file.write(byteBuffer)

out_file.close()



struct.pack을 사용해서, 2byte little-endian 형식으로 좀 더 보기 좋게 개선한 예제입니다.


import os.path

import struct


#byteBuffer = bytearray([1,0,0,0,255,255,0,0])

byteBuffer = struct.pack('hhhh',1,0,-1,0)


out_file = open('binaryfile.dat', 'wb')

for x in range(0,40000):

out_file.write(byteBuffer)

out_file.close()



generate_tone.py





반응형

+ Recent posts