I am new to Java Sounds. I want to play 2 different frequencies as an alternative for 1 second each in a cycle for a certain time. For example, if I have 2 frequencies of 440 Hz and 16000 Hz, and the time period is 10 seconds, then for each "even" second 440 Hz is reproduced for each "odd" second 16000 Hz, i.e. 5 seconds each as an alternative.
In some examples, I learned a few things, and I also made a program that runs for one frequency set by the user during the time also set by the user using these examples.
I will really appreciate if someone can help me with this. Thank.
I also attach this single frequency code for reference.
import java.nio.ByteBuffer;
import java.util.Scanner;
import javax.sound.sampled.*;
public class Audio {
public static void main(String[] args) throws InterruptedException, LineUnavailableException {
final int SAMPLING_RATE = 44100;
final int SAMPLE_SIZE = 2;
Scanner in = new Scanner(System.in);
int time = in.nextInt();
SourceDataLine line;
double fFreq = in.nextInt();
double fCyclePosition = 0;
AudioFormat format = new AudioFormat(SAMPLING_RATE, 16, 1, true, true);
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
if (!AudioSystem.isLineSupported(info)) {
System.out.println("Line matching " + info + " is not supported.");
throw new LineUnavailableException();
}
line = (SourceDataLine) AudioSystem.getLine(info);
line.open(format);
line.start();
ByteBuffer cBuf = ByteBuffer.allocate(line.getBufferSize());
int ctSamplesTotal = SAMPLING_RATE * time;
while (ctSamplesTotal > 0) {
double fCycleInc = fFreq / SAMPLING_RATE;
cBuf.clear();
int ctSamplesThisPass = line.available() / SAMPLE_SIZE;
for (int i = 0; i < ctSamplesThisPass; i++) {
cBuf.putShort((short) (Short.MAX_VALUE * Math.sin(2 * Math.PI * fCyclePosition)));
fCyclePosition += fCycleInc;
if (fCyclePosition > 1) {
fCyclePosition -= 1;
}
}
line.write(cBuf.array(), 0, cBuf.position());
ctSamplesTotal -= ctSamplesThisPass;
while (line.getBufferSize() / 2 < line.available()) {
Thread.sleep(1);
}
}
line.drain();
line.close();
}
}