Pythonを使用して任意の周波数の音を生成し、それを再生する方法を紹介します。この記事では、pygame
とnumpy
を使用して音を生成し、それを再生します。
まず、必要なライブラリをインストールします。以下のコマンドを実行してください。
pip install pygame numpy matplotlib
次に、以下のサンプルコードを使用して、任意の周波数の音を再生します。
import matplotlib.pyplot as plt
import pygame
import numpy as np
# モジュール初期化
pygame.mixer.init(frequency=44100, size=-16, channels=1)
# 再生時間を指定
time = 2
# 周波数を指定
Hz1 = 300
# 再生時間を設定
arr_size = 44100 * time * 2
x = np.linspace(0, arr_size, arr_size)
y = np.sin(2 * np.pi * Hz1 / 44100 * x) * 10000
y = y.astype(np.int16)
xtime = x / 44100
plt.plot(xtime, y)
plt.xlim(0, 0.1)
sound_arr = y.reshape(int(y.shape[0] / 2), 2)
# 音を再生
sound = pygame.sndarray.make_sound(sound_arr)
sound.play()
このコードは、指定した周波数(この場合は300Hz)の音を生成し、それを再生します。音の長さはtime
変数で指定します。この例では2秒間の音を生成しています。
このように、Pythonを使用して任意の周波数の音を生成し、それを再生することが可能です。さまざまな周波数の音を試してみて、どのように音が変わるかを確認してみてください。.