PyAudioを用いて、波形の音声をそのまま出力する。
import numpy as np
import matplotlib.pyplot as plt
import struct
import pyaudio
a = 0.1
f0 = 440
fs = 44100
sec = 3
CHUNK = 1024
n = np.arange(fs * sec)
s = a * np.sin(2.0 * np.pi * f0 * n / fs)
plt.plot(s[:int(fs/f0)])
plt.show()
s = [int(x * 32767.0) for x in s]
bin = struct.pack('h' * len(s), *s)
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16,
channels=1,
rate=fs,
output=True)
sp = 0
data = bin[sp:sp+CHUNK*2]
while len(data) > 0:
stream.write(data)
sp = sp + CHUNK*2
data = bin[sp:sp+CHUNK*2]
stream.stop_stream()
stream.close()
p.terminate()
参考
PyAudio Documentation — PyAudio 0.2.14 documentation