1
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.

sin波から音声ファイルを作る

Last updated at Posted at 2021-02-12

sin_sound.py
import wave
import numpy as np
from matplotlib import pylab as plt
import struct

a = 1     #振幅
fs = 44100 #サンプリング周波数
f0 = 440  #周波数(ラの音にあたります)
sec = 5   #秒
voice=[]

#サイン波を生成
for n in np.arange(fs * sec):
    s = a * np.sin(2.0 * np.pi * f0 * n / fs)
    voice.append(s)

#横軸:tは時間方向での離散値です.voiceの長さをサンプルレートで切っているので,サンプル数分の配列になってます.
t = np.arange(0, len(voice))/fs

#サイン波を表示
plt.plot(t,voice)
plt.xlim([0,0.01])#範囲指定0秒〜0.01秒
plt.show()

#サイン波を-32768から32767の整数値に変換(signed 16bit pcmへ)
voice = [int(x * 32767.0) for x in voice]

#バイナリ化
binwave = struct.pack("h" * len(voice), *voice)

#サイン波をwavファイルとして書き出し
w = wave.Wave_write("sin_sound.wav")
p = (1, 2, fs, len(binwave), 'NONE', 'not compressed')
w.setparams(p)
w.writeframes(binwave)
w.close()

実行は以下のコマンドで行います.

python sin_sound.py

作業ディレクトリの中に
sin_sound.wav
というファイルが作成されているはずです.
再生してみてください.

参考
https://qiita.com/MuAuan/items/ef4da6167d13cbf56e78

1
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
1
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?