Created
April 9, 2020 17:03
-
-
Save ground0state/fca36af8c0001dadfd3d2423ee24136b to your computer and use it in GitHub Desktop.
Python を使った WAVE ファイルの処理 LISENCE: CC-BY-NC-ND
This file contains hidden or 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
""" | |
喜多 一,『プログラミング演習 Python 2019( コラム編 )』, 2020-02-13, http://hdl.handle.net/2433/245698 | |
LISENCE: CC-BY-NC-ND | |
[参考資料] | |
桂田 祐史:Python を使った WAVE ファイルの処理、 http://nalab.mind.meiji.ac.jp/~mk/lecture/fourier-2018/python-sound/ (2018/12/3 アクセ ス) | |
""" | |
import numpy as np | |
import wave | |
import struct | |
# 音声ファイル名 | |
fname = 'harmonics-sq.wav' | |
wf = wave.open(fname, 'w') | |
# 音声ファイルのパラメータ、1 チャンネル(モノラル)、 | |
# 1 点の音声データ 2byte (16bit) | |
# サンプリング周波数 44.1 kHz | |
ch = 1 | |
width = 2 | |
samplerate = 44100 | |
wf.setnchannels(ch) | |
wf.setsampwidth(width) | |
wf.setframerate(samplerate) | |
# 10 秒間継続 | |
time = 10 | |
numsamples = time * samplerate | |
print("チャンネル数 = ", ch) | |
print("サンプル幅 (バイト数) = ", width) | |
print("サンプリングレート(Hz) =", samplerate) | |
print("サンプル数 =", numsamples) | |
print("録音時間 =", time) | |
print("出力ファイル = ", fname) | |
# 信号データを作る (numpy の ndarray で) | |
x = np.linspace(0, time, numsamples+1) # 0≦t≦time を numsamples 等分 | |
# 基本周の周波数 freq を 440 Hz にする | |
freq = 440 | |
# 基本波の正弦波 | |
h1 = np.sin(2 * np.pi * freq * x) | |
# 第2高調波の正弦波 | |
h2 = np.sin(2 * np.pi * 2 * freq * x) | |
# 第3高調波の正弦波 | |
h3 = np.sin(2 * np.pi * 3 * freq * x) | |
# 第4高調波の正弦波 | |
h4 = np.sin(2 * np.pi * 4 * freq * x) | |
# 第5高調波の正弦波 | |
h5 = np.sin(2 * np.pi * 5 * freq * x) | |
# 第6高調波の正弦波 | |
h6 = np.sin(2 * np.pi * 6 * freq * x) | |
# 第7高調波の正弦波 | |
h7 = np.sin(2 * np.pi * 7 * freq * x) | |
# 基本波と高調波に係数をかけて波を合成 | |
y = h1 + h2/2 + h3/3 + 0*h4/4 + h5/5 + 0*h6/6 + h7/7 | |
# [-32767,32767] の範囲に収める | |
y = np.rint(32767*y / max(abs(y))) | |
# 16 ビット整数に型変換する | |
y = y.astype(np.int16) | |
# numsamples 個のデータに打ち切る | |
y = y[0:numsamples] | |
# ndarray から bytes オブジェクトに変換 | |
data = struct.pack("h" * numsamples, *y) | |
# データを書き出す | |
wf.writeframes(data) | |
wf.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment