First of all, thanks to everyone for helping me with my previous questions.
In the following code, I take two frequencies as an alternative and write them to the .wav format to run in my Windows Media Player for a certain amount of time specified by the user. I want to understand how to loop these frequencies for an alternative start during the specified time, for example, an ambulance siren, and in my program both frequencies are played once, alternatively. For example, if I define the time as 10 seconds, then both frequencies work for 5 seconds each stretching. But I want the 1st frequency to work for a second or two seconds (as the user indicates), and then the 2nd frequency for that same second, and then the 1st frequency again, and it should continue until the specified time.
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
public class AudioWrite2New {
public static void main(String[] args) throws IOException, InterruptedException, LineUnavailableException {
Scanner in = new Scanner(System.in);
final double SAMPLING_RATE = 44100;
int time = in.nextInt();
int frequency1 = in.nextInt();
int frequency2 = in.nextInt();
float buffer[] = new float[(int) (time/2 * SAMPLING_RATE)];
float buffer1[] = new float[(int) (time/2 * SAMPLING_RATE)];
for (int sample = 0; sample < buffer.length; sample++) {
double cycle = sample / SAMPLING_RATE;
buffer[sample] = (float) (Math.sin(2 * Math.PI * frequency1 * cycle));
}
for (int sample = 0; sample < buffer1.length; sample++) {
double cycle = sample / SAMPLING_RATE;
buffer1[sample] = (float) (Math.sin(2 * Math.PI * frequency2 * cycle));
}
byte byteBuffer[] = new byte[buffer.length * 2];
byte byteBuffer1[] = new byte[buffer1.length * 2];
int count = 0;
for (int i = 0; i < byteBuffer.length; i++) {
final int x = (int) (buffer[count++] * Short.MAX_VALUE);
byteBuffer[i++] = (byte) x;
byteBuffer[i] = (byte) (x / 256);
}
count = 0;
for (int i = 0; i < byteBuffer1.length; i++) {
final int x = (int) (buffer1[count++] * Short.MAX_VALUE);
byteBuffer1[i++] = (byte) x;
byteBuffer1[i] = (byte) (x / 256);
}
byte[] merge = new byte[byteBuffer.length + byteBuffer1.length];
System.arraycopy(byteBuffer, 0, merge, 0, byteBuffer.length);
System.arraycopy(byteBuffer1, 0, merge, byteBuffer.length, byteBuffer1.length);
File out = new File("E:/RecordAudio17.wav");
AudioFormat format = new AudioFormat((float) SAMPLING_RATE, 16, 1, true, false);
ByteArrayInputStream bais = new ByteArrayInputStream(merge);
AudioInputStream audioInputStream = new AudioInputStream(bais, format, buffer1.length + buffer.length);
AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, out);
audioInputStream.close();
}
}
Java JavaSounds, . , , , .
.