Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.sound.sampled.*;
- import java.io.ByteArrayInputStream;
- import java.io.File;
- public class ArrayToWavHelper {
- private static int sampleRate = 22050;
- public static void main(String[] args) throws Exception {
- final AudioFormat frmt = new AudioFormat(sampleRate, 8, 1, true, true);
- try {
- SourceDataLine line = AudioSystem.getSourceDataLine(frmt);
- line.open(frmt);
- line.start();
- //Frequency = ... Hz for ... seconds
- byte[] bytes = generateSineWavefreq(50, 5);
- AudioInputStream ais = new AudioInputStream(new ByteArrayInputStream(bytes), frmt, bytes.length);
- AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File("test.wav"));
- play(line, bytes);
- line.drain();
- line.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- private static byte[] generateSineWavefreq(int frequencyOfSignal, int seconds) {
- // total samples = (duration in second) * (samples per second)
- byte[] sin = new byte[seconds * sampleRate];
- double samplingInterval = (double) (sampleRate / frequencyOfSignal);
- System.out.println("Sampling Frequency : " + sampleRate);
- System.out.println("Frequency of Signal : " + frequencyOfSignal);
- System.out.println("Sampling Interval : " + samplingInterval);
- for (int i = 0; i < sin.length; i++) {
- double angle = (2.0 * Math.PI * i) / samplingInterval;
- sin[i] = (byte) (Math.sin(angle) * 127);
- System.out.println("" + sin[i]);
- }
- return sin;
- }
- private static void play(SourceDataLine line, byte[] array) {
- int length = sampleRate * array.length / 1000;
- line.write(array, 0, array.length);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement