【Python】ドレミの音を演奏する

音階(音の高さ)と音価(音の長さ)を指定して、それらをつなげたものをwavファイルに書き出す。

import numpy as np
import wave
import struct

filename = "cde.wav"

a = 1.0
fs = 44100
bpm = 60

TONES = {
  'C4': 261.626,
  'D4': 293.665,
  'E4': 329.628,
  'F4': 349.228,
  'G4': 391.995,
  'A4': 440.000,
  'B4': 493.883,
  'C5': 523.251
}

melody = ([
  [['C4'], 1/4],
  [['D4'], 1/4],
  [['E4'], 1/4],
  [['F4'], 1/4],
  [['G4'], 1/4],
  [['A4'], 1/4],
  [['B4'], 1/4],
  [['C5'], 1/4]
])

sound = []
for note in melody:
  tones = note[0]
  beat = note[1]
  sec = 60 / bpm * beat * 4
  n = np.arange(fs * sec)
  s = None
  for tone in tones:
    f0 = TONES[tone] if tone in TONES else 0
    if s is None:
      s = a * np.sin(2.0 * np.pi * f0 * n / fs)
    else:
      s += a * np.sin(2.0 * np.pi * f0 * n / fs)
  sound += s.tolist()

s = np.array(sound)
abs = np.abs(s)
max_num = 32767.0 / max(abs)
s = [int(x * max_num) for x in s]

bin = struct.pack('h' * len(s), *s)

w = wave.Wave_write(filename)
p = (1, 2, fs, len(bin), 'NONE', 'not compressed')
w.setparams(p)
w.writeframes(bin)
w.close()

cde.wav

参考

Fabeee株式会社 | 伴走型DX推進(コンサルティング ✕ 実行支援)企業
タイトルとURLをコピーしました