スポンサーリンク

PySoundFileで音声/音楽データを書き出すsoundfile.write【Python】

Python

PySoundFileで音声/音楽データを書き込むには、soundfile.writeを使う。

soundfile.write – PySoundFile v0.10.0 API Documentation

以下記事を参考に、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)

soundfile.writeの使い方

第一引数fileに出力ファイル名を、第二引数dataに書き出すnumpy.ndarray配列を、第三引数にサンプルング周波数を指定する。

import soundfile

soundfile.write(file='test.wav', data=y, samplerate=sf)

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

WAV, FLAC, OGGやMATなど幅広いファイル形式が書き込む可能である。以下リンク先に書き込み可能なファイルがまとめられているので参照ください。

libsndfile
The libsndfile Home Page

関連記事、関連資料

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

コメント