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

Play audio stream with JavaFX

I'm trying to make simple audio player with JavaFX Mediaplayer component. All local files are fine but i want also implement internet radio. Code: public static void main(String[] args) throws URISyntaxException { new JFXPanel(); //init jfx…
Gravian
  • 957
  • 2
  • 11
  • 20
3
votes
1 answer

java watch processes that are using mic to record audio

please tell me is there any way to get the list of all processes that are currently using the mic to record audio ? like Skype, sound recorder both are running. want to get them in java
3
votes
4 answers

How to read an audio file? Which method should I use?

I have a panel with 2 buttons. When I click on the button 1, I'd simply like to read an audio file (a .WAV in that case). Then, when I click on the button 2, I'd like to stop the music. I do some research, but I'm a little confused about the…
Tofuw
  • 908
  • 5
  • 16
  • 35
3
votes
3 answers

Adding Music/Sound to Java Programs

I'm making some mini java games and I was wondering how I can add sound/music to my programs. I watched a video on youtube and followed the code provided, however I get the following error: java.io.IOException: could not create audio stream from…
JavaDude
  • 75
  • 1
  • 3
  • 8
3
votes
2 answers

Finding the duration a note is held MIDI

I am reading a midi file to figure out the notes and velocity of it, but how would I go about figuring out the duration the note is held? I know getData1 holds the key, and getData2 holds the velocity, but where would I figure out the duration it's…
user123446
  • 53
  • 1
  • 5
3
votes
1 answer

java.io.IOException: mark/reset not supported Java Audio Input Stream / Buffered Input Stream

I'm in the process of creating a 2D Java Platform Game and I'm trying to get audio to play from a .wav file while the game is running... Below is an AudioPlayer class I created to take care of loading the resource into an Audio Input Stream import…
Steve
  • 981
  • 1
  • 8
  • 22
3
votes
1 answer

Compare two sounds (with tolerance) in Java

I'm looking for a relatively simple way (some examples or libraries with a good API maybe?) to compare two sounds with Java (with tolerance of course). The sources are some sound files with hand-clap noises. The sound I want to compare them with is…
user2655665
  • 247
  • 1
  • 4
  • 11
3
votes
1 answer

Java Sound: devices found when run in IntelliJ, but not in SBT

I'm trying to to use Java Sound API in a Scala SBT-managed project. Here is a toy app that plays a note. import javax.sound.midi._ object MyMain extends App { val infos = MidiSystem.getMidiDeviceInfo() println( "[DEBUG] midi devices found: " +…
StokedOver9k
  • 129
  • 1
  • 9
3
votes
1 answer

How to implement Voice Activity Detection in Java?

I need to implement a voice activity detection algorithm in Java so that I can know when to start and/or stop recording audio. I am looking for an algorithm that can take either a byte[], a target-data-line, or an audio file as input. Also, a…
Skylion
  • 2,696
  • 26
  • 50
3
votes
0 answers

Linux and multiple audio lines in Java

I am trying to open several SourceDataLines in Java, and while it works on my Windows PC, it gives an error on my Raspberry Pi (soft-float Raspbian Linux) "line with format PCM_SIGNED 22050.0 Hz, 16 bit, stereo, 4 bytes/frame, little-endian not …
poochkov
  • 31
  • 1
3
votes
2 answers

Representing music audio samples in terms of dB?

I am starting a project which would allow me to use Java to read sound samples, and depending on the properties of each sample (I'm thinking focusing on decibels at the moment for the sake of simplification, or finding some way to compute the…
Legare
  • 45
  • 2
  • 7
3
votes
3 answers

Playing sound from a byte[] array

I've recieved a byte array from the server and I know that connects and sends perfectly. It's when I try and play the sound from the byte array. Here's what I have to play the sound. SourceDataLine speaker = null; try { DataLine.Info speakerInfo…
KeirDavis
  • 665
  • 2
  • 10
  • 32
3
votes
4 answers

Java - removing headers from .wav

I'm reading a .wav file into a byte array with the following code. AudioInputStream inputStream = AudioSystem.getAudioInputStream(/*my .wav file */); int numBytes = inputStream.available(); byte[] buffer = new…
William
  • 13,332
  • 13
  • 60
  • 73
3
votes
1 answer

Capturing sound from a mic

So, I went over the Java's sound tutorial and I did not find it all so helpful. Anyways, what I understood from the tutorial for recording sound from a mic is this: Although they do show how to get a target data line and so on, they do not tell…
An SO User
  • 24,612
  • 35
  • 133
  • 221
3
votes
1 answer

Get AudioInputStream from an RTMP stream in Java? Or how to mix audio of multiple RTMP streams

I need to mix the audio streams from multiple RTMP streams. I would like to use the Java Sound API, because it works well for mixing (as discussed in a previous question, Combining multiple sound streams in Java) - I have already successfully tried…
jkopp
  • 41
  • 5