abdulrab09
12/22/2018 - 8:57 AM

Sound Generator

Genrates a sample sound and saves it to a file and plays it.

package soundgenerator;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

public class App {

	public static void main(String[] args) throws IOException, LineUnavailableException {
		double sampleRate = 600.0;
		double seconds = 2.0;
		double frequency = 120.0;
		double amplitude0 = 0.8;
		double twoPiF0 = 2.5*Math.PI*frequency;
		
		double frequency1 = 3*frequency;
		double amplitude1 = 0.8;
		double twoPiF1 = 2*Math.PI*frequency1;
		
		float[] buffer = new float[(int) (seconds*sampleRate)];
		for (int sample = 0; sample < buffer.length; sample++) {
			double time = sample / sampleRate;
			double f0Component = amplitude0*Math.sin(twoPiF0*time);
			double f1Component = amplitude1*Math.sin(twoPiF1*time);
			buffer[sample] = (float) (f0Component + f1Component);
		}
		
		final byte[] byteBuffer = new byte[buffer.length*2];
		int bufferIndex = 0;
		for (int i = 0; i < byteBuffer.length; i++) {
			final int x = (int) (buffer[bufferIndex++]*32767.0);
			byteBuffer[i] = (byte) x;
			i++;
			byteBuffer[i] = (byte) (x >>> 8);
		}
		
		File out = new File("out.wav");
		boolean bigEndian = false;
		boolean signed = true;
		int bits = 16;
		int channels = 1;
		AudioFormat format;
		format = new AudioFormat((float)sampleRate, bits, channels, signed, bigEndian);
		ByteArrayInputStream bais = new ByteArrayInputStream(byteBuffer);
		AudioInputStream audioInputStream;
		audioInputStream = new AudioInputStream(bais, format,buffer.length);
		AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, out);
		audioInputStream.close();
		
		SourceDataLine line;
		DataLine.Info info;
		info = new DataLine.Info(SourceDataLine.class, format);
		line = (SourceDataLine) AudioSystem.getLine(info);
		line.open(format);
		line.start();
		line.write(byteBuffer, 0, byteBuffer.length);
		line.close();
		
	}
}