Sustain
# Take a sound and two numbers, representing the lengths of the attack
# phase of the sound, and the desired length of the sustain phase respectively.
# It returns a sustained sound.
# This function emulates a sustain effect on a guitar and works best with a
# plucked/struck instrument with well-defined attack phase, short or
# non-existent sustain, and long decay.
def sustain(sound, attLength, susLength):
length = getLength(sound)
attLength = min(attLength, length) # Input error checking and correction
# Create sustainSound, the sound "canvas"
numSamples = length + susLength
seconds = (numSamples / getSamplingRate(sound)) + 1
sustainSound = makeEmptySound(int(seconds))
#Copy attack phase
for sampleNum in range(1, attLength):
value = getSampleValueAt(sound, sampleNum)
setSampleValueAt(sustainSound, sampleNum, value)
#Copy sustain, starting immediately after the attack phase
start = attLength+1
repeatLength = 300 # Magic number, seems to work ok for the B4 note
for sampleNum in range(start, start+susLength):
value = getSampleValueAt(sound, start+(sampleNum%repeatLength))
setSampleValueAt(sustainSound, sampleNum, value)
#Copy rest of sound
start = start + susLength
for sampleNum in range(attLength+repeatLength+1, getLength(sound)+1):
value = getSampleValueAt(sound, sampleNum)
setSampleValueAt(sustainSound, sampleNum + start, value)
return sustainSound
Link to this Page