Question
Write a program called PlaySimpleSong to play a song represented as notes in text. Write the program so that it: Declares and creates a symbol
Write a program called PlaySimpleSong to play a song represented as notes in text.
Write the program so that it:
Declares and creates a symbol table using the algs31.BinarySearchST class;
Reads in a file notes_frequencies.txt where each line is a pair of strings separated by whitespace. The first string is the name of a musical note and the second a double value that is its sound frequency as found on a piano. For example, the note A4 is paired with the frequency 440 and the note C4 with the frequency 261.626. As each line is read, an entry is made in the symbol table where the note name is the key and the frequency is the value.
Reads in a song file, where each line contains a note name and a duration in seconds, separated by whitespace. A sample file is sample_simple_song.txt, which plays every C for half a second. Another song you might try is lotr.txt. Looking up the frequency corresponding to the note name, the program calls the method below to play the note.
Both the notes and frequencies file and the song file should be placed into the Eclipse data directory and, as in the GPA program, read in using StdIn and the fromFile method.
To process a text file where each line contains a fixed set of data fields:
Use the method readLine in the StdIn class, which returns a string;
Split the string into an array of strings using the instance method split in the String class;
Convert the numeric strings into numeric values using the method parseDouble in the Double class.
To play each note, place into your program and call this method:
public static void playTone(double frequency, double duration) { final int sliceCount = (int) (StdAudio.SAMPLE_RATE * duration); final double[] slices = new double[sliceCount+1]; for (int i = 0; i <= sliceCount; i++) { slices[i] = Math.sin(2 * Math.PI * i * frequency / StdAudio.SAMPLE_RATE); } StdAudio.play(slices); }
You will also have to import stdlib.StdAudio.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started