Created
October 26, 2021 08:06
-
-
Save aidiary/ed15840155475eae496d6cbc815753cb to your computer and use it in GitHub Desktop.
sounddeviceでリアルタイムにサイン波を出力
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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