Need help with a Java programming problem: You are given a file chords.txt where
ID: 3822865 • Letter: N
Question
Need help with a Java programming problem:
You are given a file chords.txt where each line contains three double values. The first value is a duration and the second and third values are frequencies. Place this file into the data folder on Eclipse.
chords.txt:
Once again you are to read values in from a file but you must be careful in doing this as different values mean different things. After you open the file, follow this pseudocode:
Note that we are now using nested loops.
To play a chord, you will need a different method and that's included here:
Explanation / Answer
//Following is the code to read chords.txt file and run chords
import java.applet.*;
import java.io.*;
import java.net.*;
import stdlib.StdAudio;
public class Chords{
//The function to play chord as provided
public static void playChord(double duration, double[] frequencies) {
final int sliceCount = (int) (StdAudio.SAMPLE_RATE * duration);
final double[] slices = new double[sliceCount+1];
for (int i = 0; i <= sliceCount; i++) {
double chord = 0.0;
for (double frequency: frequencies) {
chord += Math.sin(2 * Math.PI * i * frequency / StdAudio.SAMPLE_RATE);
}
slices[i] = chord/frequencies.length;
}
StdAudio.play(slices);
}
public static void main(String []args)throws IOException{
//Reading chords.txt file
BufferedReader br = new BufferedReader(new FileReader("chords.txt"));
String line=null;
//read file till end
while( (line=br.readLine()) != null) {
double duration; // variable to store duration
double[] frequencies= new double[2]; //frequency array of length=2
String[] splitStr = line.split("\s+"); // split the line read by spaces
duration=Double.parseDouble(splitStr[0]); //store duration
frequencies[0]=Double.parseDouble(splitStr[1]);
frequencies[1]=Double.parseDouble(splitStr[2]);
playChord(duration,frequencies); //play the chords
}
}
}