Play musical chords (JAVA PROGRAMMING)
Notes and frequencies
Every musical note has a name and a frequency. You are given a file where each line contains a note name, a tab character, and a frequence, which is a floating point value. For example, here are the first few lines from the file notes_frequencies.txt:
A0 27.5 A#0 29.1353 B0 30.8677 C1 32.7032 C#1 34.6479 D1 36.7081 D#1 38.8909 E1 41.2035 F1 43.6536
Playing chords
Write a program named PlayChords that first reads the data in the notes/frequencies file into a symbol table with the note name as the key and the frequency as the value.
The program then reads from a second file called chords.txt where each line contains one or more notes names separated by whitespace. Play the specified chords one by one by gathering the notes on each line into an array and then call the method specified below to play the resulting chord.
Here's the method that should be placed into your program.
public static void playChordOneSecond(double... frequencies) { final int sliceCount = (int) (StdAudio.SAMPLE_RATE * 1.0); final double[] slices = new double[sliceCount+1]; for (double frequency: frequencies) { for (int i = 0; i <= sliceCount; i++) { slices[i] += Math.sin(2 * Math.PI * i * frequency / StdAudio.SAMPLE_RATE); } } StdAudio.play(slices); }
Helpful information
Place the data files into the data folder in Eclipse. Copy and paste the above method into your PlayChords class.
To process a text file where each line contains a fixed set of data fields:
Please import std audio libraries first.
Then,
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scaner;
public class PlayChordsromFile {
public static void main(String [] args) {
File file = new File("risingchords.txt");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
String temp[]=new double[temp.length];
for(int i=0;i<temp.length,i++){
array[i]=Double.parseDouble(temp[i]);
}
playChord(array);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void playChord(double... frequencies) {
double duration = 0.5;
final int sliceCount = (int) (StdAudio.SAMPLE_RATE * duration);
final double[] slices = new double[sliceCount+1];
for (int i = 0; i<= sliceCount, i++) {
for (double frequency: frequencies) {
slices[i] += Math.sin(2 * Math.PI * i * frequency / StdAudio.SAMPLE_RATE);
}
slices[i] /= fequencies.length;
}
StdAudio.play(slices);
}
}
Get Answers For Free
Most questions answered within 1 hours.