Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

This is the stdaudio java file mentioned above, you can add any audi file you want. package a5; /****************************************************************************** * Compilation: javac StdAudio.java * Execution:

image text in transcribedimage text in transcribedimage text in transcribed

This is the stdaudio java file mentioned above, you can add any audi file you want. package a5; /****************************************************************************** * Compilation: javac StdAudio.java * Execution: java StdAudio * Dependencies: none * * Simple library for reading, writing, and manipulating .wav files. * * * Limitations * ----------- * - Does not seem to work properly when reading .wav files from a .jar file. * - Assumes the audio is monaural, with sampling rate of 44,100. * ******************************************************************************/ import javax.sound.sampled.Clip; // for playing midi sound files on some older systems //import java.applet.Applet; //import java.applet.AudioClip; import java.net.MalformedURLException; import java.io.File; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.IOException; import java.net.URL; import javax.sound.sampled.AudioFileFormat; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.UnsupportedAudioFileException; /** * Standard audio. This class provides a basic capability for * creating, reading, and saving audio. * 

* The audio format uses a sampling rate of 44,100 (CD quality audio), 16-bit, monaural. * *

* For additional documentation, see Section 1.5 of * Computer Science: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public final class StdAudio { /** * The sample rate - 44,100 Hz for CD quality audio. */ public static final int SAMPLE_RATE = 11025;//44100; private static final int BYTES_PER_SAMPLE = 2; // 16-bit audio private static final int BITS_PER_SAMPLE = 16; // 16-bit audio private static final double MAX_16_BIT = Short.MAX_VALUE; // 32,767 private static final int SAMPLE_BUFFER_SIZE = 4096; private static SourceDataLine line; // to play the sound private static byte[] buffer; // our internal buffer private static int bufferSize = 0; // number of samples currently in internal buffer private StdAudio() { // can not instantiate } // static initializer static { init(); } // open up an audio stream private static void init() { try { // 44,100 samples per second, 16-bit audio, mono, signed PCM, little Endian AudioFormat format = new AudioFormat((float) SAMPLE_RATE, BITS_PER_SAMPLE, 1, true, false); DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); line = (SourceDataLine) AudioSystem.getLine(info); line.open(format, SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE); // the internal buffer is a fraction of the actual buffer size, this choice is arbitrary // it gets divided because we can't expect the buffered data to line up exactly with when // the sound card decides to push out its samples. buffer = new byte[SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE/3]; } catch (LineUnavailableException e) { System.out.println(e.getMessage()); } // no sound gets made before this call line.start(); } /** * Closes standard audio. */ public static void close() { line.drain(); line.stop(); } /** * Writes one sample (between -1.0 and +1.0) to standard audio. * If the sample is outside the range, it will be clipped. * * @param sample the sample to play * @throws IllegalArgumentException if the sample is {@code Double.NaN} */ public static void play(double sample) { // clip if outside [-1, +1] if (Double.isNaN(sample)) throw new IllegalArgumentException("sample is NaN"); if (sample +1.0) sample = +1.0; // convert to bytes short s = (short) (MAX_16_BIT * sample); buffer[bufferSize++] = (byte) s; buffer[bufferSize++] = (byte) (s >> 8); // little Endian // send to sound card if buffer is full if (bufferSize >= buffer.length) { line.write(buffer, 0, buffer.length); bufferSize = 0; } } /** * Writes the array of samples (between -1.0 and +1.0) to standard audio. * If a sample is outside the range, it will be clipped. * * @param samples the array of samples to play * @throws IllegalArgumentException if any sample is {@code Double.NaN} * @throws IllegalArgumentException if {@code samples} is {@code null} */ public static void play(double[] samples) { if (samples == null) throw new IllegalArgumentException("argument to play() is null"); for (int i = 0; i > 8); } // now save the file try { ByteArrayInputStream bais = new ByteArrayInputStream(data); AudioInputStream ais = new AudioInputStream(bais, format, samples.length); if (filename.endsWith(".wav") || filename.endsWith(".WAV")) { AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File(filename)); } else if (filename.endsWith(".au") || filename.endsWith(".AU")) { AudioSystem.write(ais, AudioFileFormat.Type.AU, new File(filename)); } else { throw new IllegalArgumentException("unsupported audio format: '" + filename + "'"); } } catch (IOException ioe) { throw new IllegalArgumentException("unable to save file '" + filename + "'", ioe); } } /** * Plays an audio file (in .wav, .mid, or .au format) in a background thread. * * @param filename the name of the audio file * @throws IllegalArgumentException if unable to play {@code filename} * @throws IllegalArgumentException if {@code filename} is {@code null} */ public static synchronized void play(final String filename) { if (filename == null) throw new IllegalArgumentException(); InputStream is = StdAudio.class.getResourceAsStream(filename); if (is == null) { throw new IllegalArgumentException("could not read '" + filename + "'"); } // code adapted from: http://stackoverflow.com/questions/26305/how-can-i-play-sound-in-java try { // check if file format is supported // (if not, will throw an UnsupportedAudioFileException) AudioSystem.getAudioInputStream(is); new Thread(new Runnable() { @Override public void run() { stream(filename); } }).start(); } // let's try Applet.newAudioClip() instead catch (UnsupportedAudioFileException e) { // playApplet(filename); return; } // something else went wrong catch (IOException ioe) { throw new IllegalArgumentException("could not play '" + filename + "'", ioe); } } // https://www3.ntu.edu.sg/home/ehchua/programming/java/J8c_PlayingSound.html // play a wav or aif file // javax.sound.sampled.Clip fails for long clips (on some systems) private static void stream(String filename) { SourceDataLine line = null; int BUFFER_SIZE = 4096; // 4K buffer try { InputStream is = StdAudio.class.getResourceAsStream(filename); AudioInputStream ais = AudioSystem.getAudioInputStream(is); AudioFormat audioFormat = ais.getFormat(); DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat); line = (SourceDataLine) AudioSystem.getLine(info); line.open(audioFormat); line.start(); byte[] samples = new byte[BUFFER_SIZE]; int count = 0; while ((count = ais.read(samples, 0, BUFFER_SIZE)) != -1) { line.write(samples, 0, count); } } catch (IOException e) { e.printStackTrace(); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (LineUnavailableException e) { e.printStackTrace(); } finally { if (line != null) { line.drain(); line.close(); } } } /** * Loops an audio file (in .wav, .mid, or .au format) in a background thread. * * @param filename the name of the audio file * @throws IllegalArgumentException if {@code filename} is {@code null} */ public static synchronized void loop(String filename) { if (filename == null) throw new IllegalArgumentException(); // code adapted from: http://stackoverflow.com/questions/26305/how-can-i-play-sound-in-java try { Clip clip = AudioSystem.getClip(); InputStream is = StdAudio.class.getResourceAsStream(filename); AudioInputStream ais = AudioSystem.getAudioInputStream(is); clip.open(ais); clip.loop(Clip.LOOP_CONTINUOUSLY); } catch (UnsupportedAudioFileException e) { throw new IllegalArgumentException("unsupported audio format: '" + filename + "'", e); } catch (LineUnavailableException e) { throw new IllegalArgumentException("could not play '" + filename + "'", e); } catch (IOException e) { throw new IllegalArgumentException("could not play '" + filename + "'", e); } } /*************************************************************************** * Unit tests {@code StdAudio}. ***************************************************************************/ // create a note (sine wave) of the given frequency (Hz), for the given // duration (seconds) scaled to the given volume (amplitude) private static double[] note(double hz, double duration, double amplitude) { int n = (int) (StdAudio.SAMPLE_RATE * duration); double[] a = new double[n+1]; for (int i = 0; i Post-Condition: The array parameter is not changed. Example: Calling frequencyCount([0,0,1,1,1,7]) would return [2,3,0,0,0,0,0,1,0,0] since there are 2 zeroes and 3 ones and 1 seven, and no other digits in the parameter array 6. Method name: reverseSound Parameter(s): A double array Return value: Returns a double array that has its elements in reversed order from the parameter array. Post-Condition: The array parameter is not changed. Example: Calling reverseSound([0.1, 0.2, 0.3, 0.5]) should return a new array [0.5, 0.3, 0.2, 0.1] 7. Method name: scaleSound Parameter(s): A double array and a double value. Return value: Returns a double array that has as its elements each of the parameter array elements scaled by the second parameter Post-Condition: The array parameter is not changed. Example: Calling scalesound(.0,-0.1, 0.3], 2.0) should return a new array [O.0,-02. O.6] Note: The play method for sounds keeps all values in the required -1.0 to 1.0 range, you do not need to test for this like you did in the Picture brightening. 8. Method name: echoSound Parameter(s): A double array, an int specifying how many samples offset the echo starts at, and a double giving a weight to the echo. The double array will have at least as many values as the offset. Return value: A double array as long as the array parameter plus the offset parameter. The first offset samples will be the same as the first offset samples as the parameter array. The last offset samples will be the same as the last offset samples from the parameter array scaled by the weight parameter. The middle samples will be the sample from the parameter array plus the sample from the parameter array back the offset amount scaled by the weight parameter. Here is the logic of it. An echo is a diminished sound delayed from bouncing off a distance object. So if you yell, I first hear your original signal. Then when the bounce comes back, I hear your original signal plus a scaled down signal from back in time. Then, when you stop, I only hear the scaled down signal from back in time Post-Condition: The array parameter is not changed. Example: Calling echoSound([0.1, 0.2,0.3, 0.4], 1, 0.5) should return a new array of length 5 (the original array plus the offset). The new array is [0.1, 0.25. O.4, 0.55, 0.21. The 0.1 is before the echo starts and is unchanged. 0.5). The last value is all echo, and is 0.4 0.5 9. Method name: smoothSound Parameter(s): A double array with at least 3 elements in it. Return value: Returns a double array that has as its elements a sliding average of the parameter array elements. More precisely: 1. The first and last elements of the new array are the same as the first and last elements of the parameter array, respectively. 2. For the other elements of the new array, for an element at index i, it is equal to the average of elements from the parameter array at indices i-1, i, and i+1 Post-Condition: The array parameter is not changed Example: Calling smoothSound([O.O. O.2, O.7, 0.21) should return a new array [O.. . O 3666 played, noise in the sound should be reduced. 0 21, when If you want to hear the effect of these sound methods, you can add code in main like this: double[] samples-StdAudio.read("asyouwish2.wav") StdAudio.play(samples); doublel] reversed reverseSound (samples); StdAudio.play (reversed); Note that this isn't really a test-it is to help you appreciate the kinds of effects we can generate pretty easily in code. A test has an expected output for a given input to a method. Post-Condition: The array parameter is not changed. Example: Calling frequencyCount([0,0,1,1,1,7]) would return [2,3,0,0,0,0,0,1,0,0] since there are 2 zeroes and 3 ones and 1 seven, and no other digits in the parameter array 6. Method name: reverseSound Parameter(s): A double array Return value: Returns a double array that has its elements in reversed order from the parameter array. Post-Condition: The array parameter is not changed. Example: Calling reverseSound([0.1, 0.2, 0.3, 0.5]) should return a new array [0.5, 0.3, 0.2, 0.1] 7. Method name: scaleSound Parameter(s): A double array and a double value. Return value: Returns a double array that has as its elements each of the parameter array elements scaled by the second parameter Post-Condition: The array parameter is not changed. Example: Calling scalesound(.0,-0.1, 0.3], 2.0) should return a new array [O.0,-02. O.6] Note: The play method for sounds keeps all values in the required -1.0 to 1.0 range, you do not need to test for this like you did in the Picture brightening. 8. Method name: echoSound Parameter(s): A double array, an int specifying how many samples offset the echo starts at, and a double giving a weight to the echo. The double array will have at least as many values as the offset. Return value: A double array as long as the array parameter plus the offset parameter. The first offset samples will be the same as the first offset samples as the parameter array. The last offset samples will be the same as the last offset samples from the parameter array scaled by the weight parameter. The middle samples will be the sample from the parameter array plus the sample from the parameter array back the offset amount scaled by the weight parameter. Here is the logic of it. An echo is a diminished sound delayed from bouncing off a distance object. So if you yell, I first hear your original signal. Then when the bounce comes back, I hear your original signal plus a scaled down signal from back in time. Then, when you stop, I only hear the scaled down signal from back in time Post-Condition: The array parameter is not changed. Example: Calling echoSound([0.1, 0.2,0.3, 0.4], 1, 0.5) should return a new array of length 5 (the original array plus the offset). The new array is [0.1, 0.25. O.4, 0.55, 0.21. The 0.1 is before the echo starts and is unchanged. 0.5). The last value is all echo, and is 0.4 0.5 9. Method name: smoothSound Parameter(s): A double array with at least 3 elements in it. Return value: Returns a double array that has as its elements a sliding average of the parameter array elements. More precisely: 1. The first and last elements of the new array are the same as the first and last elements of the parameter array, respectively. 2. For the other elements of the new array, for an element at index i, it is equal to the average of elements from the parameter array at indices i-1, i, and i+1 Post-Condition: The array parameter is not changed Example: Calling smoothSound([O.O. O.2, O.7, 0.21) should return a new array [O.. . O 3666 played, noise in the sound should be reduced. 0 21, when If you want to hear the effect of these sound methods, you can add code in main like this: double[] samples-StdAudio.read("asyouwish2.wav") StdAudio.play(samples); doublel] reversed reverseSound (samples); StdAudio.play (reversed); Note that this isn't really a test-it is to help you appreciate the kinds of effects we can generate pretty easily in code. A test has an expected output for a given input to a method

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Learning PostgreSQL

Authors: Salahaldin Juba, Achim Vannahme, Andrey Volkov

1st Edition

178398919X, 9781783989195

More Books

Students also viewed these Databases questions

Question

=+1. What is a stakeholder? Define the term in your own words.

Answered: 1 week ago