[程式語言] 音樂 python--第一課 聲波合成 - 精華區

[程式語言] 音樂 python--第一課 聲波合成

特種兵

特種兵圖像(預設)

2019-09-29 15:22:21

From:1.161.149.232

上次我們介紹 python 與音樂用的市 jython 必須安裝 java.
這次我們改用純 python.

首先聲音必須靠振動產生,下面這個範例會先用數學函數產生三種基本的振動波形:square(方波)'triangle(三角波)和 sawtooth(鋸齒波)。
接著會把這三種波形作任意組合產生些微的音色差異。
執行這個程式會把所有產生的波形存成 wave 音檔,您可以先用媒體播放軟體逐一收聽看看他們的差別。

waves.py:


# 振盪器合成
import matplotlib.pyplot as plt
plt.plot([0,1],[1,-1],"r-",[0,.5,1],[-1,1,-1],"b-",[0,.5],[1,1],"g-",[.5,1],[-1,-1],"g-",linewidth=8)
plt.xlabel(r"sample time")
plt.ylabel(r"amplitude")
plt.show()
# 一秒鐘的取樣聲音
from numpy import linspace, append
from scipy.io.wavfile import read, write
freqSamp=44100
freqNote=210
numRpts=freqSamp//freqNote
print(freqNote,numRpts)
test=linspace(1.0,-1.0,16,False).astype(float)
print(test)
test2=append(test,test)
print(test2)
sawData=linspace(1.0,-1.0,numRpts,False).astype(float)
rpts=freqNote-1
sawNote=sawData
while rpts>0:
     sawNote=append(sawNote,sawData)
     rpts=rpts-1
print(r"sawtooth",sawNote.shape)
write("sawtooth.wav",freqSamp,sawNote)
halfRpts=numRpts//2
firstHalf=linspace(-1.0,1.0,halfRpts,False).astype(float)
lastHalf=linspace(1.0,-1.0,halfRpts,False).astype(float)
triData=append(firstHalf,lastHalf)
rpts=freqNote-1
triNote=triData
while rpts>0:
     triNote=append(triNote,triData)
     rpts=rpts-1
print("triangle",triNote.shape)
write("triangle.wav",freqSamp,triNote)
firstHalf=linspace(1.0,1.0,halfRpts,False).astype(float)
lastHalf=linspace(-1.0,-1.0,halfRpts,False).astype(float)
squData=append(firstHalf,lastHalf)
rpts=freqNote-1
squNote=squData
while rpts>0:
     squNote=append(squNote,squData)
     rpts=rpts-1
print("square",squNote.shape)
write("square.wav",freqSamp,squNote)
# 兩種波形組合
sawtriNote=(sawNote+triNote)/2
print("saw and tri")
write("sawtri.wav",freqSamp,sawtriNote)
trisquNote=(triNote+squNote)/2
print("tri and squ")
write("trisqu.wav",freqSamp,trisquNote)
squsawNote=(squNote+sawNote)/2
print("squ and saw")
write("squsaw.wav",freqSamp,squsawNote)
# 三種波形組合
sawtrisquNote=(sawNote+triNote+squNote)/3
print("all three")
write("sawtrisqu.wav",freqSamp,sawtrisquNote)
# 讀入並組合
(rate,saw)=read("sawtooth.wav")
(rate,squ)=read("square.wav")
(rate,tri)=read("triangle.wav")
print(rate,saw)
print(rate,squ)
print(rate,tri)
print("saw3squ2tri1")
mixNote=saw/2+squ/3+tri/6
write("saw3squ2tri1.wav",rate,mixNote)

※最後更新時間:2019-09-28 19:10:14 From:123.193.249.19 By:coscell


來源文章


最後更新:2019-09-29 15:22:21

From: 1.161.149.232

By: 特種兵