I'm really new to sound processing, and so far I have been able to understand (with a lot of help and criticism : P ) how to (1) take 2 and then generate audio from it, alternatively. Then (2) write this audio file as a .wav file that can be played by media players. Then (3) instead of time, I took user input in the form of bits (maximum 8 bytes), and when there was β0β at this input, I took the 1st frequency, and in the case of the 1st frequency. I am attaching the above code, '(3)' , only to help someone who needs it.
If you want to see my previous code, click here.
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;
public class AudioBits {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
final double SAMPLING_RATE = 44100;
float timeInterval = in.nextFloat();
int frequency1 = in.nextInt();
int frequency2 = in.nextInt();
while (!in.hasNext("[0-1]{1,8}")) {
System.out.println("Wrong input.");
in.next();
}
String binary = in.next();
int value = Integer.parseInt(binary, 2);
int binVal = 0b10000000;
float buffer[] = new float[((int) (timeInterval * SAMPLING_RATE)) / 1000];
float buffer1[] = new float[((int) (timeInterval * SAMPLING_RATE)) / 1000];
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++) {
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++) {
int x = (int) (buffer1[count++] * Short.MAX_VALUE);
byteBuffer1[i++] = (byte) x;
byteBuffer1[i] = (byte) (x / 256);
}
byte[] merge = new byte[8 * byteBuffer.length];
for (int i = 0; i < 8; i++) {
int c = value & binVal;
if (c == 0) {
System.arraycopy(byteBuffer, 0, merge, i * (byteBuffer.length), byteBuffer.length);
} else {
System.arraycopy(byteBuffer1, 0, merge, i * (byteBuffer.length), byteBuffer1.length);
}
binVal = binVal >> 1;
}
File out = new File("E:/RecordAudio30.wav");
AudioFormat format = new AudioFormat((float) SAMPLING_RATE, 16, 1, true, false);
ByteArrayInputStream bais = new ByteArrayInputStream(merge);
AudioInputStream audioInputStream = new AudioInputStream(bais, format, (long) (8 * (byteBuffer.length / 2)));
AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, out);
audioInputStream.close();
}
}