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
6
votes
3 answers

Java ogg to wav conversion

I have the following code snippet: File file = new File(sourceFile); AudioInputStream in = AudioSystem.getAudioInputStream(file); AudioInputStream din = null; AudioFormat baseFormat = in.getFormat(); AudioFormat decodedFormat = new AudioFormat( …
Peter Jaloveczki
  • 2,039
  • 1
  • 19
  • 35
6
votes
1 answer

Obtain wave pattern of a audio file in Java

I'm wondering how I may obtain musical information such as amplitude from a audio file? Suppose we have a raw audio file, what I want to extract data from the file which allows me to generate a curve such as…
user1767408
  • 61
  • 1
  • 2
6
votes
1 answer

javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file when loading wav file

i am using java 6 , and i am trying to load wav file, to get its duration as follows: public static double getAudioFileDuration(File file) { try { AudioInputStream stream = AudioSystem.getAudioInputStream(file); //…
Mahmoud Saleh
  • 33,303
  • 119
  • 337
  • 498
6
votes
2 answers

Java midi volume control won't work

I've been trying to get midi volume control to work in a MidiPlayer class for a very long time now. I've searched for examples for accomplishing this here on stackoverflow and all over the Internet, but nothing I try ever seems to work. The volume…
Cazra
  • 143
  • 10
5
votes
2 answers

Noise in background when generating sine wave in Java

I'm getting a slight distortion (sounds like buzzing) in the background when I run the following code. Because of its subtle nature it makes believe there is some sort of aliasing going on with the byte casting. AudioFormat = PCM_SIGNED 44100.0 Hz,…
worbel
  • 6,509
  • 13
  • 53
  • 63
5
votes
1 answer

Java sound recording and mixer settings

I'm using the javax.sound.sampled package in a radio data mode decoding program. To use the program the user feeds audio from their radio receiver into their PC's line input. The user is also required to use their mixer program to select the line in…
IanW
  • 1,304
  • 2
  • 17
  • 26
5
votes
0 answers

Use ASIO with Gervill Synthesizer in Java

I am using Gervill's software synthesizer to load an SF2 soundbank, and play music from a Midi keyboard, and I was wondering if it's possible to play the output through ASIO, probably through JAsioHost. I've been trying to look through the Gervill…
Josh Wood
  • 1,598
  • 3
  • 16
  • 21
5
votes
2 answers

Play variable tone with Java?

Back in my high school Pascal class, I had a fun little program that would take in an integer and then play a tone using the system speaker. The pitch of the tone would vary, based on the int. Does functionality like this exist in the Java world? …
IVR Avenger
  • 15,090
  • 13
  • 46
  • 57
5
votes
1 answer

Java sound - LineUnavailableException:

I am using the following code for loading a clip (javax.sound.sampled.Clip) def createClip(file:String):Clip = { val clip = AudioSystem.getClip() clip.open(AudioSystem.getAudioInputStream(new File(s"sounds/$file.wav"))) clip } Its…
Julian
  • 525
  • 5
  • 19
5
votes
3 answers

How to get Note On/Off messages from a MIDI sequence?

I am hoping to get notifications of note on/off events in a playing MIDI sequence to show the notes on a screen based (piano) keyboard. The code below adds a MetaEventListener and a ControllerEventListener when playing a MIDI file, but only shows a…
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
5
votes
1 answer

Converting raw bytes into audio sound

In my application I inherit a javastreamingaudio class from the freeTTS package then bypass the write method which sends an array of bytes to the SourceDataLine for audio processing. Instead of writing to the data line, I write this and subsequent…
Afro Genius
  • 177
  • 1
  • 2
  • 9
5
votes
0 answers

Does the Java Sound API have access to sound being played by other (non-java) applications?

I've been reading up on the Java Sound API for the last few weeks and I still can't figure out if this is possible. I ask because I want to write a program that takes sound data passing through the system headed for an output line, like my…
Will Byrne
  • 681
  • 7
  • 15
5
votes
1 answer

Capture entire Windows sound output?

I have had a look at the AudioSystem class but can't seem to figure out how I would go about getting the output stream of the audio in Windows, i.e. what you hear coming out of the speakers? Then I want to be able to get this input stream and then…
jackgerrits
  • 791
  • 2
  • 8
  • 20
5
votes
2 answers

How to get PCM data from a wav file?

I have a .wav file. I want to get the PCM data from that sound file, so that I can get the individual data chunks from the sound and process it. But I don't know how to do it. Can anyone tell me how to do it? I have done this so far: public class…
Pallab
  • 179
  • 1
  • 3
  • 16
5
votes
1 answer

Downsampling audio from 44.1kHz to 16kHz in Java

I have an application that records a speech sample from the user's microphone and uploads it to a server which then does some stuff with it. It seems I must record with the following parameters to avoid an IllegalArgumentException: Encoding…
Woobie
  • 85
  • 2
  • 5