Section 9.4. Reversing a Sound

[Page 304 (continued)]

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.

[Page 305]
Program 78. Reverse a Sound

/**  * Method to reverse the current sound.  */ public void reverse() {   Sound orig = new Sound(this.getFileName());   int length = this.getLength();   // loop through the samples   for (int targetIndex = 0, sourceIndex = length  1;        targetIndex < length && sourceIndex > 0;        targetIndex++, sourceIndex)     this.setSampleValueAt(targetIndex,                           orig.getSampleValueAt(sourceIndex)); }

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.explore(); > s.reverse(); >; > s.explore();

[Page 306]

Figure 9.4. Comparing the original sound (left) to the reversed sound (right).

Introduction to Computing & Programming Algebra in Java(c) A Multimedia Approach
Introduction to Computing & Programming Algebra in Java(c) A Multimedia Approach
Year: 2007
Pages: 191 © 2008-2017.
If you may any questions please contact us: