ファイル名:sound.py
# coding: utf-8
import wave
from pylab import *
import struct
import scipy.signal
import numpy as np
import os
def openFile(filename, printInfo=1):
wf = wave.open(filename , "r" )
fs = wf.getframerate() # サンプリング周波数
x = wf.readframes(wf.getnframes())
x = frombuffer(x, dtype= "int16") / 32768.0 # -1 - +1に正規化
if printInfo == 1:
printWaveInfo(wf)
wf.close()
return x, fs, wf.getnchannels(), wf.getnframes()
def saveFile(data, fs, bit, filename, channel=1):
print("channel", channel)
data = [int(v * 32767.0) for v in data]
data = struct.pack("h" * len(data), *data)
w = wave.Wave_write(filename + ".wav")
w.setnchannels(channel)
w.setsampwidth(int(bit/8))
w.setframerate(fs)
w.writeframes(data)
w.close()
def printWaveInfo(wf):
"""WAVEファイルの情報を取得"""
print ("チャンネル数:", wf.getnchannels())
print ("サンプル幅:", wf.getsampwidth())
print ("サンプリング周波数:", wf.getframerate())
print ("フレーム数:", wf.getnframes())
print ("パラメータ:", wf.getparams())
print ("長さ(秒):", float(wf.getnframes()) / wf.getframerate())
def stereo2monoral(sig):
monoral = []
for i in range(0,len(sig), 2):
monoral.append(sig[i])
return np.array(monoral)
def preEmphasis(signal, p):
"""プリエンファシスフィルタ"""
# 係数 (1.0, -p) のFIRフィルタを作成
return scipy.signal.lfilter([1.0, -p], 1, signal)
def nomalize(x, xmax, xmin, a):
min = 1 / 32768.0
try:
z = a * (x - xmin) / (xmax - xmin)
except ZeroDivisionError:
z = a * (x - xmin) / min
#print ("1e-7")
#print (1e-7)
return z
def parentpath(path=__file__, f=0):
return str('/'.join(os.path.abspath(path).split('/')[0:-1-f]))