Created
June 12, 2022 14:52
-
-
Save rniwase/7225728ca11a4338a03733711416ade6 to your computer and use it in GitHub Desktop.
WAVファイルの無音部分を区切りとしてファイルを分割する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
usage: python3 ./sample_sxtractor *.wav | |
''' | |
import sys | |
import copy | |
import wave | |
import numpy as np | |
from scipy import signal | |
# import matplotlib.pyplot as plt | |
# import matplotlib.transforms as mtransforms | |
LEN_FILT = 10000 | |
THRESH = 200. | |
if __name__ == "__main__": | |
filename = sys.argv[1] | |
wave_ary = [] | |
indata_params = [] | |
with wave.open(filename, "r") as in_data: | |
smp_num_frames = in_data.getnframes() | |
indata_params = in_data.getparams() | |
wave_ary = in_data.readframes(smp_num_frames) | |
wave_ary = np.frombuffer(wave_ary, dtype="int16") | |
wave_ary = wave_ary.reshape((-1,2)) | |
wave_mix = np.sum(wave_ary, axis=1) * 0.5 | |
wave_abs = np.abs(wave_mix) | |
wave_flt = signal.convolve(wave_abs, np.ones(LEN_FILT), mode='same') / LEN_FILT | |
wave_thr = np.array(wave_flt >= THRESH, dtype="int16") * LEN_FILT | |
wave_flt2 = signal.convolve(wave_thr, np.ones(LEN_FILT), mode='same') / LEN_FILT | |
wave_thr2 = np.array(wave_flt2 >= THRESH) | |
index = [] | |
tmp = [0, 0] | |
for i in range(len(wave_thr2)-1): | |
if (wave_thr2[i] == False) and (wave_thr2[i+1] == True): | |
tmp[0] = i | |
if (wave_thr2[i] == True) and (wave_thr2[i+1] == False): | |
tmp[1] = i | |
index.append(copy.copy(tmp)) | |
print(index) | |
# fig, ax = plt.subplots() | |
# trans = mtransforms.blended_transform_factory(ax.transData, ax.transAxes) | |
# ax.plot(wave_abs, ) | |
# ax.fill_between(np.arange(smp_num_frames), 0, smp_num_frames, wave_thr2, | |
# facecolor='red', alpha=0.5, transform=trans) | |
# ax.set_ylim([0, np.max(wave_abs)*1.2]) | |
# plt.show() | |
count = 0 | |
filename_split = filename.split(".") | |
for i in index: | |
filename_split_tmp = copy.copy(filename_split) | |
filename_split_tmp.insert(-1, str(count)) | |
out_data = wave.Wave_write(".".join(filename_split_tmp)) | |
out_data.setparams(indata_params) | |
out_data.writeframes(wave_ary[i[0]:i[1]]) | |
count += 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment