1

I am very new in Java Sound and therefore my concepts of it are not that strong. I want to understand that how to write the audio generated by the following code into a file of .wav format. I had read a few posts and some questions on stackoverflow as well, but I am not able to make out the solution out of them. So please help me understand it. Thanks.

import javax.sound.sampled.*;
import java.nio.ByteBuffer;
import java.util.Scanner;

public class Audio {           //Alternating Tones

public static void main(final String[] args) throws LineUnavailableException, InterruptedException {

    Scanner in = new Scanner(System.in);

    int alterTime = in.nextInt();       //For the time between frequencies
    int time = in.nextInt();            //Time specified by the user
    int freq1 = in.nextInt();           //Value of 1st Frequency specified by user
    int freq2 = in.nextInt();           //Value of 2nd Frequency specified by user


    final Clip clip1 = alternatingClip(freq1);          //For example 440
    final Clip clip2 = alternatingClip(freq2);          //For example 880


    //Adds a listener to this line. Whenever the line's status changes, the listener's update() method is called 
    //with a LineEvent object that describes the change.
    clip1.addLineListener(event -> {

        //getType() Obtains the event's type, which in this case should be equal to LineEvent.Type.STOP
        if (event.getType() == LineEvent.Type.STOP) {
            clip2.setFramePosition(0);      //Sets the media position
            clip2.loop(alterTime);
        }
    });

    //Adds a listener to this line. Whenever the line's status changes, the listener's update() method is called 
    //with a LineEvent object that describes the change.
    clip2.addLineListener(event -> {

        //getType() Obtains the event's type, which in this case should be equal to LineEvent.Type.STOP
        if (event.getType() == LineEvent.Type.STOP) {
            clip1.setFramePosition(0);      //Sets the media position
            clip1.loop(alterTime);
        }
    });


    clip1.loop(alterTime);

    Thread.sleep(1000*time);     // prevent JVM from exiting
}

public static Clip alternatingClip(final float frequency) throws LineUnavailableException {
    Clip clip = AudioSystem.getClip();
    final int SAMPLING_RATE = 44100;
    AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, SAMPLING_RATE, 16, 1, 2, SAMPLING_RATE, true);

    final ByteBuffer buffer = ByteBuffer.allocate(SAMPLING_RATE * format.getFrameSize());
    final float cycleFraction = frequency / format.getFrameRate();
    double cyclePosition = 0;
    while (buffer.hasRemaining()) {         //Returns true only if there is at least one element remaining in the buffer
        buffer.putShort((short) (Short.MAX_VALUE * Math.sin(2 * Math.PI * cyclePosition)));
        cyclePosition += cycleFraction;
        if (cyclePosition > 1) {
            cyclePosition -= 1;
        }
    }
    // (AudioFormat, byte[] data, int offset, int bufferSize)
    clip.open(format, buffer.array(), 0, buffer.capacity());    
    return clip;
}
}
Vibhav Chaddha
  • 349
  • 4
  • 14
  • 1
    *"I had read a few posts and some questions on stackoverflow as well"* Provide links to them. *"..but I am not able to make out the solution out of them."* Why not? There is not much motivation to help someone if we expect you to come back with *"I am not able to make out the solution out of this"* - it you can't understand those answers, there is good reason to expect you won't understand ours. – Andrew Thompson Nov 22 '16 at 15:12
  • @AndrewThompson Actually, the posts that I had read were somewhat different to what I was looking for. For example some were using 'swing', 'JFrame', 'JButton' etc and at this time I don't have much idea about them. Although with every post I had learned something new but I was not able to resolve my problem and my inexperience maybe one of the reasons for that. I am attaching some of the links that I had seen in my next comment. And I never wanted to offend anyone, I wrote it just out of pure ignorance. Thanks. – Vibhav Chaddha Nov 23 '16 at 06:21
  • @AndrewThompson [link](http://alvinalexander.com/java/java-audio-example-java-au-play-sound) [link](http://www.developer.com/java/other/article.php/2226701/Java-Sound-Creating-Playing-and-Saving-Synthetic-Sounds.htm) [link](http://stackoverflow.com/questions/15526255/best-way-to-get-sound-on-button-press-for-a-java-calculator) Thanks. – Vibhav Chaddha Nov 23 '16 at 06:21

0 Answers0