Skip to content

Instantly share code, notes, and snippets.

@aidiary
Created October 26, 2021 08:06
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save aidiary/ed15840155475eae496d6cbc815753cb to your computer and use it in GitHub Desktop.
sounddeviceでリアルタイムにサイン波を出力
import numpy as np
import sounddevice as sd
samplerate = 44100
frequency = 440.0
amplitude = 0.6
sd.default.samplerate = samplerate
sd.default.device = 'MacBook Proのスピーカー'
start_idx = 0
try:
# framesのブロック単位でsin波を出力
# ブロック単位の処理なのでブロックをまたいでどこまで処理したかをstart_idxに記録しておく
def callback(outdata, frames, time, status):
global start_idx
# サンプル単位
n = (start_idx + np.arange(frames))
# (samples, channels)
n = n.reshape(-1, 1)
# サイン波は時間単位 t = n / samplerate にしてから生成
outdata[:] = amplitude * np.sin(2.0 * np.pi * frequency * n / samplerate)
# 次のブロックの開始地点を移動
start_idx += frames
with sd.OutputStream(callback=callback):
input()
except KeyboardInterrupt:
exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment