9.2. Create a Sound ClipSometimes a sound is too long and you want just part of it. This can happen when you record a sound. There may be silence before and after the actual sound. Or, you may want to pull one word out of a sound. You can "clip" a sound just as we clipped a picture by copying just part of the sound. What if we want to pull the "This" out of the sound thisisatest.wav? How can we tell where it ends? Open an explorer on the sound using sound.explore();. Click at the first flat area after the first non-flat area (silence should have values near 0). Click the PLAY BEFORE button to play the part of the sound before the current index. You can use the arrow buttons to change the current index as well. Using the explorer we see that the word "this" ends at about 8,500 (Figure 9.1). Figure 9.1. Exploring the "This is a test'' to find the end of the first word. |
/** * Method to create a new sound by copying just part of * the current sound to a new sound * @param start the index to start the copy at (inclusive) * @param end the index to stop the copy at (inclusive) * @return a new sound with just the samples from start to * end in it */ public Sound clip(int start, int end) { //calculate the number of samples in the clip |
Notice that we said that we would return a Sound object from this method by saying that the type of thing returned is from the class Sound. At the end of the method, we use the keyword return followed by the variable that refers to the new Sound object. So in order to refer to this new Sound object again, we will need to declare a variable and set the value of that variable to refer to the returned Sound object.
> Sound test = new Sound(FileChooser.getMediaPath("thisisatest.wav")); > test.explore(); > Sound s1 = test.clip(0,8500); > s1.play(); > s1.explore();
Use the explorer on the original sound and the clipped sound. Change the number of samples between pixels to be 100 in the clipped sound. Then compare the sample values. Convince yourself that the clipped sound does have the same values as the original (Figure 9.2).