Skip to content

Instantly share code, notes, and snippets.

@KatsuhiroMorishita
Last active June 22, 2017 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KatsuhiroMorishita/4a107a9c6eea457977220f558cab53fc to your computer and use it in GitHub Desktop.
Save KatsuhiroMorishita/4a107a9c6eea457977220f558cab53fc to your computer and use it in GitHub Desktop.
waveファイルを一定時間ごとに切断して別のファイルとして保存するPythonのスクリプトです。今思うと、いきなり全部のデータをメモリ上に読み出さなくても良かったんですが、まぁ良いですよね?(笑)
# waveファイルを一定の時間毎に切断する
# author: Katsuhiro Morishita
# created: 2017-06-21
# lisence: MIT
import glob
import wave
import os.path
term = 60.0 # 切断後のファイルの時間幅[s]
fnames = glob.glob("*.wav")
for fname in fnames:
if "split" in fname:
continue
root, ext = os.path.splitext(fname)
wf = wave.open(fname , "r" )
g = wf.readframes(wf.getnframes()) # bytes data, 波形データ読み出し
ch, sampwidth, fs, nframes, comptype, compname = wf.getparams()
amount = nframes * ch * sampwidth # 音源ファイルのデータ量[byte]
read_amount = int(fs * sampwidth * ch * term)
rp = 0
index = 0
while rp < amount:
data = g[rp : rp+read_amount] # スライス
with wave.open("{0}_split{1:02d}.wav".format(root, index), mode="wb") as fw:
fw.setparams((
ch, # channel
sampwidth, # byte width
fs, # sampling rate
len(data), # number of frames
comptype,
compname
))
fw.writeframes(data)
rp += read_amount
index += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment