-1

I have been searching for how to play audio in java ( textpad ). There are plenty of examples but they use a GUI. I am using a command line interface. How do I play audio and use key event e.g spacebar to pause the audio and press spacebar again to replay the audio?

darclander
  • 1,526
  • 1
  • 13
  • 35

1 Answers1

0

I do not know which examples you have been looking at but I do not think the GUI has anything to do with IF you can play sounds.

The following code is a simple sound class you can use in order to play audio in Java, you can read more about it at this Documentation.

import javax.sound.sampled.*;
import java.io.IOException;
import java.net.URL;

public class Sound {
    private URL url;
    private Clip clip;
/**
 * @param requestedSound The requested type of sound
 */
public Sound(String requestedSound) {
    url = this.getClass().getResource(requestedSound);
    if (url != null) {
        try {
            // Open an audio input stream.
            // Get a sound clip resource.
            // Open audio clip and load samples from the audio input stream.
            AudioInputStream audioInput = AudioSystem.getAudioInputStream(url);
            clip = AudioSystem.getClip();
            clip.open(audioInput);


        } catch (UnsupportedAudioFileException | LineUnavailableException | IOException e) {
            e.printStackTrace();
        }

    }
}

/**
 * Plays the sound
 */
public void play() {
    clip.setFramePosition(0);
    clip.start();
}
}

To use it you simply create a sound in your main file, with Sound mySound = new Sound("path_to_sound"); Where you replace path_to_sound with your path. I believe one of the supported formats is .wav. Then you can just play the sound whenever you want to with mySound.play();, and whenever you do it will be played from the beginning.

Regarding your implementation of using spacebar to play / replay the audio, I believe it is better if you try to work with the given code in order to understand how it works.

darclander
  • 1,526
  • 1
  • 13
  • 35