-I am trying to write a program that reads in text files and plays them as music notes. I have a folder that contains the text files named 'music' and when I run my program I have a JFileChooser that asks me which text file I would like to play. I select the file from the music folder, but regardless of which one I choose it only plays the first file: Ascale.txt. I know I have it hard coded in the main method but when I change that file name to one of the other files, my program only plays the Ascale.txt over and over. Here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JFileChooser;
public class PlayThatTune {
public static double[] tone(double hz, double t) {
int sps = 44100;
int N = (int) (sps * t);
double[] a = new double[N+1];
for (int i = 0; i <= N; i++)
a[i] = Math.sin(2 * Math.PI * i * hz / sps);
return a;
}
public static double[] note(int p, double t) {
double hz = 440 * Math.pow(2, p / 12.0);
double[] a = tone(hz, t);
double[] hi = tone(2*hz, t);
double[] lo = tone(hz/2, t);
double[] h = sum(hi, lo, .5, .5);
return sum(a, h, .5, .5);
}
public static double[] sum(double[] a, double[] b, double awt, double bwt) {
//superpose a and b, weighted
double[]c = new double[a.length];
for(int i = 0; i < a.length; i++)
c[i] = a[i] * awt + b[i] * bwt;
return c;
}
public static void main(String[] args) throws FileNotFoundException {
//Create a file chooser
final JFileChooser fc = new JFileChooser(".");
fc.showOpenDialog(null);
getSelectedFile();
Scanner in = new Scanner(new File("music/Ascale.txt"));
// repeat as long as there are more tokens to read in
while (in.hasNext()) {
// read in the pitch, where 0 = concert A (above middle C)
int pitch = in.nextInt();
// read in duration in seconds
double duration = in.nextDouble();
// build sine wave with desired frequency
double hz = 440 * Math.pow(2, pitch / 12.0);
int N = (int) (StdAudioOut.SAMPLE_RATE * duration);
double[] a = new double[N+1];
for (int i = 0; i <= N; i++) {
a[i] = Math.sin(2 * Math.PI * i * hz / StdAudioOut.SAMPLE_RATE);
}
// play it using standard audio
StdAudioOut.play(a);
}
}
private static void getSelectedFile() {
}
}
I would appreciate any help!
没有评论:
发表评论