Questions tagged [javasound]

Use this tag for questions about the Java Sound APIs. These are for the capture, processing, and playback of sampled audio data and for sequencing and synthesis of MIDI data.

Java Sound

The Java Sound API provides functionality for the capture, processing, and playback of sampled audio data and the sequencing and synthesis of MIDI data.

Java Sound was incorporated into the J2SE in Java 1.3.

Sampled Sound

The javax.sound.sampled package:

Provides interfaces and classes for capture, processing, and playback of sampled audio data.

Playing a Clip

import java.net.URL;
import javax.swing.*;
import javax.sound.sampled.*;

public class LoopSound {

    public static void main(String[] args) throws Exception {
        URL url = new URL("http://pscode.org/media/leftright.wav");
        Clip clip = AudioSystem.getClip();
        // getAudioInputStream() also accepts a File or InputStream
        AudioInputStream ais = AudioSystem.getAudioInputStream(url);
        clip.open(ais);
        clip.loop(Clip.LOOP_CONTINUOUSLY);
        SwingUtilities.invokeLater(() -> {
            // A GUI element to prevent the Clip's daemon Thread
            // from terminating at the end of the main()
            JOptionPane.showMessageDialog(null, "Close to exit!");
        });
    }
}

Playing a SourceDataLine

import java.net.URL;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioFormat.Encoding;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.Line.Info;

public class ExampleSourceDataLine {

    public static void main(String[] args) throws Exception {
        
        // Name string uses relative addressing, assumes the resource is  
        // located in "audio" child folder of folder holding this class.
        URL url = ExampleSourceDataLine.class.getResource("audio/371535__robinhood76__06934-distant-ship-horn.wav");
        // The wav file named above was obtained from https://freesound.org/people/Robinhood76/sounds/371535/ 
        // and matches the audioFormat.
        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(url);
        
        AudioFormat audioFormat = new AudioFormat(
                Encoding.PCM_SIGNED, 44100, 16, 2, 4, 44100, false);
        Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
        SourceDataLine sourceDataLine = (SourceDataLine)AudioSystem.getLine(info);
        sourceDataLine.open(audioFormat);
        
        int bytesRead = 0;
        byte[] buffer = new byte[1024];
        sourceDataLine.start();
        while((bytesRead = audioInputStream.read(buffer)) != -1)
        {
            // It is possible at this point manipulate the data in buffer[].
            // The write operation blocks while the system plays the sound.
            sourceDataLine.write(buffer, 0, bytesRead);                                 
        }   
        sourceDataLine.drain();
        // release resources
        sourceDataLine.close();
        audioInputStream.close();
    }
}

MIDI Sequences

The javax.sound.midi package:

Provides interfaces and classes for I/O, sequencing, and synthesis of MIDI (Musical Instrument Digital Interface) data.

Playing a MIDI Sequence

import javax.sound.midi.*;
import javax.swing.*;
import java.net.URL;

class PlayMidi {

    public static void main(String[] args) throws Exception {
        URL url = new URL("http://pscode.org/media/EverLove.mid");

        Sequence sequence = MidiSystem.getSequence(url);
        Sequencer sequencer = MidiSystem.getSequencer();

        sequencer.open();
        sequencer.setSequence(sequence);

        sequencer.start();
        SwingUtilities.invokeLater(() -> {
            // A GUI element to prevent the Sequencer's daemon Thread
            // from terminating at the end of the main()
            JOptionPane.showMessageDialog(null, "Close to exit!");
        });
    }
}

Service Provider Interface

The Java Sound API uses a Service Provider Interface to identify encoders & decoders for sound formats and sequence types. This way, adding support for a new format or type is as simple as providing a decoder and/or encoder for it, adding an SPI file to the manifest of the Jar it is in, then adding the Jar to the run-time class-path of the application.

Java Sound Capabilities

The capabilities of the sampled sound API can be obtained using such methods as AudioSystem.getAudioFileTypes() & AudioSystem.getMixerInfo().

MIDI capabilities can be obtained using methods such as MidiSystem.getMidiFileTypes() & MidiSystem.getMidiDeviceInfo().

MP3 decoding support

The Java Sound API does not support many formats of sampled sound internally. In a 1.8.0_65 Oracle JRE getAudioFileTypes() will generally return {WAVE, AU, AIFF}. An MP3 decoder at least, is close by. The mp3plugin.jar of the Java Media Framework supports decoding MP3s. Another alternative that is suitable for MP3 playback is using the JavaFX MediaPlayer.

Applet AudioClip

Applet provides a convenience AudioClip object. AudioClip is similar to the Java Sound Clip, but not as versatile. Java Sound can be used in applets. Applets however have been deprecated as of Java 9. This class should not to be confused with javafx.scene.media.AudioClip, present since JavaFX 2.0, which is also similar to the Java Sound Clip but with additional capabilities.

See Also

  • The Java Sound trail in the Java Tutorial.
  • Java Sound API: Java Sound Demo. The Java Sound Demo showcases how the Java Sound API can be used for controlling audio playback, audio capture, MIDI synthesis, and basic MIDI sequencing.
  • Java Sound API in the JavaDocs
  • javax.sound.sampled
  • javax.sound.sampled.spi
  • javax.sound.midi
  • javax.sound.midi.spi
  • Java Sound Resources (archive). While these examples are relatively old, the Java Sound API was complete at the time they were prepared, and they cover most of the tasks you might want to do with sound. The examples were prepared by two people who were heavily involved during the early design of the Java Sound API, & they distilled years of experience with sound & Java Sound into this resource. Well worth checking out.

Helpful Q&As for Java Sound

929 questions
5
votes
2 answers

Java Program to create a PNG waveform for an audio file

How can you convert a Wav file into a PNG waveform image file using Java? java MyProgram.class [path to wav file] [path where to write png file] Expected results: Png saved in path specified is a waveform of the wav file passed in.
Nicholas DiPiazza
  • 10,029
  • 11
  • 83
  • 152
5
votes
1 answer

Need help getting control of my computer's main output Speaker

At the moment I am trying to use a JSlider in Java to control the master volume of my PC. So far I have been able to locate my PC's main speaker's port. However, I do not know how to successfully call it and run a method like getValue() or…
Eric after dark
  • 1,768
  • 4
  • 31
  • 79
5
votes
1 answer

How to cut silence in the end of a wav file using Java?

How can I erase the silence (lower then the threshold) part of a wav file using Java? Some say "pull samples out of the PCM data". How can I do that?
javatar
  • 115
  • 11
5
votes
4 answers

Is there a WMA spi for javasound?

I poked around the internet a bit but had no luck. Does anyone know if one exists?
Nico
  • 1,181
  • 2
  • 17
  • 35
4
votes
3 answers

Failed to passing InputStream object to Java Sound API

It works with a File object being passed to AudioSystem#getAudioFileFormat, but why does it fail with an InputStream object below? Any suggestion? import java.io.*; import javax.sound.sampled.*; public class Test { public static void…
sof
  • 9,113
  • 16
  • 57
  • 83
4
votes
1 answer

Reading a wav file java vs matlab

I am trying to read data of a .wav file both in java and matlab and save as an array of bytes. In java the code looks as follows: public byte[] readWav2(File file) throws UnsupportedAudioFileException, IOException { AudioFormat audioFormat; …
Radek
  • 1,403
  • 3
  • 25
  • 54
4
votes
5 answers

Fast Audio Input/Output

Here's what I want to do: I want to allow the user to give my program some sound data (through a mic input), then hold it for 250ms, then output it back out through the speakers. I have done this already using Java Sound API. The problem is that…
Brandon Montgomery
  • 6,924
  • 3
  • 48
  • 71
4
votes
1 answer

java sequencer playlist

I currently have a very simple class: public class Music { private Sequence sequence; private Sequencer sequencer; public Music(String music) { try { this.sequence =…
Bv202
  • 3,924
  • 13
  • 46
  • 80
4
votes
3 answers

List input and output audio devices in Applet

I am running a signed applet that needs to provide the ability for the user to select the input and output audio devices ( similar to what skype provides). I borrowed the following code from other thread: import javax.sound.sampled.*; public class…
Johnny Everson
  • 8,343
  • 7
  • 39
  • 75
4
votes
4 answers

How to record sound from just line-in port with Java

I need to capture sounds from line-in port, not microphone. Although I accomplished recording from microphone, I can not accomplish capturing sounds from line-in ports or specific ports. How can I handle this problem?
Erdinç Kaya
  • 61
  • 1
  • 6
4
votes
4 answers

Java AudioSystem and TargetDataLine

I am trying to capture audio from the line-in from my PC, to do this I am using AudioSystem class. There is one of two choices with the static AudioSystem.write method: Write to a file Or Write to a stream. I can get it to write to a file just fine,…
worbel
  • 6,509
  • 13
  • 53
  • 63
4
votes
2 answers

Increase playback speed of sound file in java

I'm looking for information on how I can increase the playback speed of a sound file using Java and it's sound API. I'm currently using a clip and an AudioInputStream to play back the file, but I'll be glad to change that if it means I can increase…
Varun Madiath
  • 3,152
  • 4
  • 30
  • 46
4
votes
3 answers

Java: How to get current frequency of audio input?

I want to analyse the current frequency of the microphone input to synchronize my LEDs with the music playing. I know how to capture the sound from the microphone, but I don't know about FFT, which I often saw while searching for a solution to get…
Jannik
  • 399
  • 2
  • 5
  • 22
4
votes
4 answers

manipulating audio and drawing waveform using java sound in real-time

I am currently developing an application that helps the user to tune his guitar and generate guitar effects. This is in real-time. I've been looking through java applications that could give an idea to generate guitar effects such as overdrive and…
Christina Salipot
4
votes
3 answers

Problem with a Java thread that captures sound card data

I have a program which creates a thread that captures data from the soundcard at 48 KHz and writes it to a buffer for collection. The heart of the thread code is as follows .. public void run() { // Run continously for (;;) { …
IanW
  • 1,304
  • 2
  • 17
  • 26