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
1 answer

Is it possible to use the mute button as an input in programming?

Hey so I was using Spotify yesterday and I noticed while an ad was playing that any time I mute my volume or drop the volume to zero, spotify pauses the ad and doesn't resume until you turn the volume back up. I started thinking about that and got…
3
votes
2 answers

Concatenation of two WAV files failed

I have this simple code to concatenate two wav files. Its pretty simple and the code runs without any errors. But there is a problem with the output file. The output file generated does not play, and surprisingly its size is only 44 bytes whereas my…
Nick Div
  • 5,338
  • 12
  • 65
  • 127
3
votes
2 answers

Java detecting an audio file (mp3)

I have this code that reads an mp3 file import java.io.File; import java.io.IOException; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.UnsupportedAudioFileException; public class Sound { public static void…
KyelJmD
  • 4,682
  • 9
  • 54
  • 77
3
votes
2 answers

how do I get Mixer channels layout in java

I thought I can find anything on this great site but now I seem to face the issue with no answer :) Please help! Thing is, I need to play up to 6 different wav files with 1 channel each into 6 channels supported by system mixer (left, right,…
Cynichniy Bandera
  • 5,991
  • 2
  • 29
  • 33
3
votes
2 answers

Playing a sine wave of varying pitch

I have a (pretty simple) piece of code I've thrown together which plays a sine wave of a specific frequency and plays it - it works no problem: public class Sine { private static final int SAMPLE_RATE = 16 * 1024; private static final int…
Michael Berry
  • 70,193
  • 21
  • 157
  • 216
3
votes
3 answers

Why does Java Sound behave differently when I run from a .jar?

The play method below is from a class which, upon instantiation, reads a .wav file into a byte array called data, and stores the sound format in an AudioFormat object called format. I have a program that calls play from a java.util.Timer. When I go…
Vectornaut
  • 473
  • 5
  • 11
3
votes
2 answers

How to get a reference to a non default MIDI Sequencer?

I am building a Java application that programatically generates a MIDI Sequence that is then sent over the LoopBe Internal Midi Port so that I can use Ableton Live instruments for better sound playback quality. Please correct me if I am wrong. What…
nunos
  • 20,479
  • 50
  • 119
  • 154
3
votes
2 answers

JAAD stopping other providers from working

I'm using JAAD with SPI to play m4a files through JavaSound, which I have working fine. However, I'd like to support a number of formats in this way - but whenever I try and play another format, JAAD seems to try to deal with it and then fail…
Michael Berry
  • 70,193
  • 21
  • 157
  • 216
3
votes
1 answer

regular "clicking" with javax.sound.sampled

I try to output some sound with Scala. My problem is that i get a short "noise"/"click" every second. I didn't had this problem with a similar java program. Has somebody an idea what is wrong? Scala 2.9.2 java 1.6.0_31 OS X 10.7.3 import…
Fabian
  • 1,224
  • 1
  • 11
  • 26
3
votes
3 answers

How to cast from InputStream to AudioInputStream

Is it possible to cast from an InputStream to an AudioInputStream? I want to play little sound files at certain events, so I made following SoundThread import java.io.*; import javax.sound.sampled.*; public class SoundThread implements Runnable{ …
Valentino Ru
  • 4,964
  • 12
  • 43
  • 78
3
votes
2 answers

Looking for Java wrapper for Windows DirectSound/WASAPI/? audio

After spending quite a bit of time trying to design my way around the existing javax.sound.sampled library for simple (but relatively time-accurate) capture/rendering of audio, I'm concluding that I really need to get to the native audio API. The…
ags
  • 719
  • 7
  • 23
3
votes
4 answers

Wav file convert to byte array in java

My project is 'Speech Recognition of Azeri speech'. I have to write a program that converts wav files to byte array. How to convert audio file to byte[]?
user1367678
  • 41
  • 1
  • 1
  • 2
3
votes
1 answer

Video - sound - sensor capture in Java

I would like to develop an application which would be able to capture video from a webcam, capture sound from a mic and capture movement if a proximity sensor is available. Initially I want it to run on windows but if able I might want to make it…
Emil Anca
  • 153
  • 1
  • 10
3
votes
1 answer

Close a looping javax.sound.sampled clip

I'm probably approaching this incorrectly but I need to find out how to stop a looping javax.sound.sampled clip. I have 9 different sounds. I want a different sound to play as a user presses an increase amplitude button. At the moment I'm calling…
Al D
  • 657
  • 2
  • 10
  • 27
2
votes
0 answers

How to distinguish between DirectAudioDevice and PortMixer mixers?

I am enumerating mixers with AudioSystem.getMixerInfo(). I found that returning mixers are sometimes duplicated. Investigation showed, that 4 mixers returned are of class DirectAudioDevice and 6 mixers are of class PortMixer. Both classes are…
Dims
  • 47,675
  • 117
  • 331
  • 600