-
Your starting point is a function that decreases the volume of a sound by a constant factor.
def decreaseVolume(sound):
for sampleIndex in range(0,getLength(sound)):
value = getSampleValueAt(sound,sampleIndex)
setSampleValueAt(sound,sampleIndex,value * 0.5)
-
You can test this function as usual:
>>> filename = pickAFile()
>>> sound = makeSound(filename)
>>> decreaseVolume(sound)
>>> play(sound)
-
Now modify the function by first changing the for statement to decrease only the second half of the samples. For this you have to compute the index of the sample in the middle of the sound.
-
Then you have to change the multiplier that is applied for each sample in that second half. Start by initializing a variable by 1.0. Then figure out how much to decrease that multiplier at each step. Consider the following example: If there are 1000 samples, and you start with 1.0, you want to decrease the multiplier at each step by a one thousandth = 0.001.
-
Finally, modify the function yet once more again so that the original sound (object) is not modified. For this you have to use the function makeEmptySound(samples) to create a new sound, which is long enough to contain the original sound. Note: In the first edition of the book makeEmptySound() takes the number of seconds as argument. However, the version of JES we are using takes the number of samples as argument.
-
Then, instead of modifying the samples in the second half of the sound do the following things: copy the samples in the first half of the sound and then copy the samples in the second half of the sound, but this time modify the sample value during the copy operation. As the last step return the modified sound by using the return statement as the last line of the function as follows:
def function(argument):
...
newsound = makeEmptySound(...)
...
return newsound
-
You can then test that this works correctly by:
>>> filename = pickAFile()
>>> originalsound = makeSound(filename)
>>> modified = decreaseVolume(originalsound)
>>> play(originalsound)
>>> play(modified)
The first play statement should play the original, unmodified sound. The second play statement should play the new, modified sound. If this is the case, everything works correctly.
Here are a couple of sample sounds files. You have to right-click and select "Save Link As..." to download them.