简体   繁体   中英

How do you write a method that plays chords in Java using StdAudio?

I am currently writing a method that plays chords but I ran into a bit of trouble. I am able to produce sound but all I get are snippets of white noise. I have listed my method below.

    public static void playChord(double duration, double... frequencies) {
            final int sliceCount = (int) (StdAudio.SAMPLE_RATE * duration);
            final double[] slices = new double[sliceCount + 1];
            double freqTotal=0;
            for (int i = 0; i <= sliceCount; i++) {
                for (int j=0; j<frequencies.length;j++) {
                    frequencies[j] +=frequencies[j];
                    freqTotal=frequencies[j];
                }
                slices[i] = Math.sin(2 * Math.PI * i * freqTotal/StdAudio.SAMPLE_RATE);
            }
            StdAudio.play(slices);
        }

There are two issues here:

The first is that you are stomping on your frequencies array with the frequencies[j] += frequencies[j] line on each and every sample. Assume frequencies[0] == 100 . Before you generate the first sample it is going to change to 200. Even if the length of the frequencies array was only 1 then this is not going to produce a sine wave.

Issue number two is that your concept of combining multiple frequencies is wrong. Assume the frequencies array has two elements of 100 and 200. If the first problem were fixed you would actually compute a single sine at 300 Hz. That's because you are adding them together at the wrong level so you are computing 'sin(2*pi i (100+200)/2) which is sin(2*pi*i*300/2) .

Instead you need to do something like this:

 for (int i = 0; i < sliceCount; i++)
 {
     for (int j = 0 ; j < frequencies.length; j++)
     {
         slices[i] += Math.sin(2*Math.PI*i*frequencies[i]/StdAudio.SAMPLE_RATE);
     }
     slices[i] /= frequencies.length; // renormalize to between -1 and 1
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM