# oscillators for mixing

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('sample  time')
plt.ylabel('amplitude')
plt.show()

#  samples of 1 second duration

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('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)

# mixing in pairs

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)

# mixing all three waveforms

sawtrisquNote=(sawNote+triNote+squNote)/3

print('all three')

write('sawtrisqu.wav',freqSamp,sawtrisquNote)

# reading and mixing


(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)