23 Oct 2016
Changing the volume ( amplitude ) of sounds
In this article we are gonna play with amplitude of sounds. We will learn how to increase or decrease volume by manipulating amplitude. As we know amplitude of sound is the main factor in volume. Increasing or decreasing amplitude means increasing volume or decreasing volume. We defined three methods ( increaseVolume, decreaseVolume & changeVolume ) in mysound class.
Note : You can’t increase or decrease volume of your device with this code. So, don’t confuse yourself. we are just changing amplitude and it does not mean anything else.
package Sounds; import bookClasses.FileChooser; import bookClasses.SimpleSound; import bookClasses.SoundSample; public class MySound extends SimpleSound { /** * Constructor that takes a file name * @param fileName the name of the file */ public MySound(String fileName) { // let the parent class handle setting the file name super(fileName); } /** * Increase the volume ( amplitude ) of sound */ public void increaseVolume() { SoundSample[] sampleArray = this.getSamples(); SoundSample sample = null; int value = 0; int index = 0; // loop through all the samples in the array while (index < sampleArray.length) { sample = sampleArray[index]; value = sample.getValue(); sample.setValue(value * 2); index++; } } /** * Decrease the volume ( amplitude ) of sound */ public void decreaseVolume() { SoundSample[] sampleArray = this.getSamples(); SoundSample sample = null; int value = 0; int index = 0; // loop through all the samples in the array while (index < sampleArray.length) { sample = sampleArray[index]; value = sample.getValue(); sample.setValue((int) (value * 0.5)); index++; } } public void changeVolume(double factor) { SoundSample[] sampleArray = this.getSamples(); SoundSample sample = null; int value = 0; // loop through all the samples in the array for (int i = 0; i < sampleArray.length; i++) { sample = sampleArray[i]; value = sample.getValue(); sample.setValue((int) (value * factor)); } } public static void main(String[] args) { //open a sound file e.g. WAV file String fileName = FileChooser.pickAFile(); //Create instance of sound MySound sound = new MySound(fileName); //Get sound samples SoundSample[] sampleArray = sound.getSamples(); //increase sound volume //sound.increaseVolume(); sound.changeVolume(.5); //Play sound sound.play(); } }