9.4. Reversing a Sound
In the splicing example, we copied the samples from the words just as they were in the original sound. We don't have to always go in the same order. We can reverse the wordsor make them faster, slower, louder, or softer. For an example, here's a method that reverses a sound so that you can play it backward.
Program 78. Reverse a Sound
This method first creates another Sound object from the same file as the current Sound object. This will make a copy of the original sound. Next the method saves the length of the current Sound object. Then it loops.
The loop initializes the value of targetIndex to 0, and the value of sourceIndex to the length of the sound minus 1. It loops while targetIndex is less than the length of the sound and the sourceIndex is greater than 0. It increments targetIndex by 1 after the body of the loop and it decrements the value of sourceIndex by one each time through the loop.
Why does it start sourceIndex at the length of the sound minus 1 and decrement it each time through the loop? Remember that the last valid index is at the length minus 1, which is why the sourceIndex starts with this value. So we copy from the end of the source sound (length 1) to the beginning of the target sound (0) during the first execution of the loop. The second time through the loop we copy from the next to last sound sample in the source (length 2) to the second position in the target (1). We will keep looping until the targetIndex equals the length of the sound.
To use this method to reverse a sound try (Figure 9.4):
> Sound s = new Sound(FileChooser.getMediaPath("croak.wav")); > s.play(); > s.explore(); > s.reverse(); > s.play(); > s.explore();
Figure 9.4. Comparing the original sound (left) to the reversed sound (right).