スポンサーリンク

【SciPy】音声/音楽データを書き出すscipy.io.wavfile.write【Python】

Python

PythonのライブラリSciPyで音声/音楽データを書き出すには、scipy.io.wavfile.writeを使う。

Numpyで生成した、サンプリング周波数44100Hz、振幅0.5、長さ3秒、1000Hzの正弦波を書き出します。

import numpy as np
import matplotlib.pyplot as plt

A = 0.5    # 振幅
f = 1000.0    # 周波数 Hz
sec = 3.0  # 信号の長さ s
sf = 44100 # サンプリング周波数 Hz

t = np.arange(0, sec, 1/sf) #サンプリング点の生成

y = A*np.sin(2*np.pi*f*t) # 正弦波の生成

plt.plot(t, y)

scipy.io.wavfile.writeの使い方

第一引数filenameに出力ファイル名を、第二引数rateにサンプルング周波数を、第三引数dataに書き出したい信号のndarray配列を指定します。

import scipy
from scipy.io.wavfile import write

scipy.io.wavfile.write(filename='test.wav', rate=sf, data=y)

対応フォーマットについて

scipy.io.wavfile.writeはwavファイルのみ対応しています。いくつかのWAV formatに対応しており、dataに指定した配列のNumPy dtype によって自動的に決められます。

WAV formatMinMaxNumPy dtype
32-bit floating-point-1.0+1.0float32
32-bit PCM-2147483648+2147483647int32
16-bit PCM-32768+32767int16
8-bit PCM0255uint8

関連記事、関連資料

  • GitHubコード
python-sampler/scipy-wavfile-write.ipynb at main · take-tech-09/python-sampler
Contribute to take-tech-09/python-sampler development by creating an account on GitHub.

コメント