0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

指定した周波数の音のwavファイルを作成する

Posted at
noisy_doremi.py
#ノイジーなドレミファソラシドのwavファイルを作成する
import numpy as np
import wave
import struct
import matplotlib.pyplot as plt
from numpy import zeros
import random

fname = 'doremifasorashido.wav'
wf = wave.open(fname, 'w')
ch = 1                          #チャンネル数は1CH(モノラル)
width = 2                       #サンプルサイズは2バイト
samplerate = 44100              #サンプリングレートは44.1kHz
wf.setnchannels(ch)             
wf.setsampwidth(width)          
wf.setframerate(samplerate)

time = 10                       #10秒
all_samples = time * samplerate #データ総数(10×44100個)

# 信号データを作る (numpy の ndarray で)
freq = [261.6, 293.7, 329.6, 349.2, 392, 440, 493.9, 523.3] # 周波数はドレミファソラシド の周波数[Hz]
x = np.linspace(0, time, all_samples+1) # all_samplesを周波数freqの数で分割
y = zeros(all_samples)                  # all_samples分の0行列を作成
slice = int(all_samples/len(freq))      
for i,j in enumerate(freq):
    noise = np.random.rand(slice)       #あえてノイズを加える。あえてね。
    y[slice*i:slice*(i+1)] = np.sin(2*np.pi*j*x[slice*i:slice*(i+1)]) + noise # 周波数 freq[Hz] の正弦波

y = np.rint(32767*y/max(abs(y)))        # [-32767,32767] の範囲に収める
y = y.astype(np.int16)                  # 16ビット整数に型変換する
y = y[0:all_samples]                    # all_samples 個のデータに打ち切る

# ndarray から bytes オブジェクトに変換
data = struct.pack("h" * all_samples , *y)

# データを書き出す
wf.writeframes(data)
wf.close() 
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?