#!/usr/bin/env python # coding: utf-8 # In[1]: get_ipython().run_line_magic('matplotlib', 'inline') import numpy as np import matplotlib.pyplot as plt # ## 請安裝 # # conda install pyaudio # In[2]: import pyaudio # In[3]: p = pyaudio.PyAudio() # In[4]: volume = 0.5 # range [0.0, 1.0] fs = 44100 # sampling rate, Hz, must be integer duration = 1.0 # in seconds, may be float f = 440.0 # sine frequency, Hz, may be float # In[5]: # generate samples, note conversion to float32 array samples = (np.sin(2*np.pi*np.arange(fs*duration)*f/fs)).astype(np.float32).tobytes() # In[6]: # for paFloat32 sample values must be in range [-1.0, 1.0] stream = p.open(format=pyaudio.paFloat32, channels=1, rate=fs, output=True) # In[7]: stream.write(samples) # In[8]: stream.stop_stream() stream.close() # In[9]: p.terminate() # In[11]: len(np.sin(2*np.pi*np.arange(fs*duration)*f/fs)) # In[13]: t = np.linspace(0, 1, fs) # In[22]: y = np.sin(2*np.pi*f*t).astype(np.float32) # In[23]: plt.plot(t, y) plt.xlim(0, 0.01) # In[24]: samples = y.tobytes() # In[26]: p = pyaudio.PyAudio() stream = p.open(format=pyaudio.paFloat32, channels=1, rate=fs, output=True) # In[27]: stream.write(samples) # In[28]: stream.stop_stream() stream.close() # In[29]: p.terminate()