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

pausing mp3 in java

I'm currently working on a project in which i need to play a background mp3 sound. I managed to do that using the Jlayer library and a piece of code found here However, I needed to add some more features to this code, such as loop playing and…
Aserre
  • 4,916
  • 5
  • 33
  • 56
3
votes
2 answers

JavaX MIDI - Play MIDI file with custom soundfont

I was trying to implement a MIDI player for a java program. So I started using the javax.sound.midi library. I load my Sequencer and my Synthesizer there: private void playMidiFile() { Soundbank soundfont =…
mrdlink
  • 266
  • 4
  • 15
3
votes
1 answer

Built-in click sound

Windows has built-in system sounds like win.sound.exclamation, win.sound.asterisk, etc. By built-in, I mean these sounds already exist on the operating system and I don't need to rely on providing a sound file to my program. I have code that…
MrPickles
  • 1,255
  • 1
  • 16
  • 31
3
votes
0 answers

Making java react to a spike in outgoing sound

I'm trying to beat a game made by my friend. The game goes as follows: A baby will spawn at a random location on my screen. i then have to move the mouse over it, and react,by clicking it, as soon as it starts to scream. I have used the…
3
votes
3 answers

Playing sound of a particular frequency in android

I want to play a sound of a particular frequency in android based on user input, somewhat similar to guitar application. Can anyone tell me how to do that? Do i need to have all freq sounds in the res\raw folder?
Ashwin
  • 132
  • 3
  • 13
3
votes
1 answer

Java sound doesn't work after I stop it

This is just the test file, I have my Sound class and I am invoking it from another main class. It plays for 3 sec, and then it stops, then it doesn't play again. What might be the issue? This is driving me crazy. Sound Class public class Sound { …
KiranGautam
  • 142
  • 1
  • 11
3
votes
0 answers

Java: Generating Audio and saving it in a .wav format

I am really new in sound processing and till date I have been able to understand (with a lot of help and criticism :P ) how to (1) take 2 frequencies and then generate audio out of it, alternatively. Then, (2) write that audio as a .wav file that…
Vibhav Chaddha
  • 431
  • 7
  • 15
3
votes
2 answers

Play 2 different frequencies alternatively in Java

I am a newbie in Java Sounds. I want to play 2 different frequencies alternatively for 1 second each in a loop for some specified time. Like, if I have 2 frequencies 440hz and 16000hz and the time period is 10 seconds then for every 'even' second…
Vibhav Chaddha
  • 431
  • 7
  • 15
3
votes
0 answers

javax.sound.sampled - trying to start audio sample repeatedly doesn't work

I am programming a little drum sequencer, a roland tr808 knockoff with 16 steps/measure and 16 instruments(=drum samples). User has a gui where he can thus create a 16x16 pattern. However, if a sample is played more than once in quick succession, it…
3
votes
1 answer

Changing Volume with JLayer

I have a very specific problem with JLayer in my Music-Player project. I want to include something to adjust the volume, but it seems it isn't that easy to implement. This is because JLayer isn't supporting it from itself. I excluded the Player…
Schesam
  • 583
  • 5
  • 19
3
votes
1 answer

Exception in reading an MP3 file through AudioSystem.getAudioInputStream(file)

I am trying to read an MP3 file through class javax.sound.sampled.AudioSystem but I am getting an UnsupportedAudioFileException. My code trying to read the audio file looks like:- AudioInputStream audioInputStream = …
Vineet Tyagi
  • 300
  • 1
  • 15
3
votes
2 answers

getDuration on mp3 file streams: java.io.IOException: mark/reset not supported

I use getDuration on a local MP3file successfully, but when getDuration on a remote MP3stream results in an error: java.io.IOException: mark/reset not supported. Successful getDuration on local MP3: public static void getDurationOff() throws…
cheng
  • 1,196
  • 2
  • 12
  • 16
3
votes
2 answers

How to get duration of audio file?

I want to get duration (total time) of audio file in seconds. Audio file can be of any format I.E. (.mp3, .wav, .wma etc.). try { File file = new File("C:/Users/Administrator/AppData/Local/Temp/" + "01 - Ab Tere Bin Jee Lenge…
programminglover
  • 753
  • 3
  • 10
  • 20
3
votes
1 answer

javax.sound.sampled.LineUnavailableException

I'm working on in a java project that helps people to learn the location of countries in the map. The program plays a .wav sound file when the mouse passes over an object and works perfectly running in Windows but today I tried to so the same…
Sandoval0992
  • 1,307
  • 3
  • 18
  • 24
3
votes
1 answer

Java Use a Clip and a Try - with - resources block which results with no sound

I am rewriting my AudioManager class for my school project and I encountered a problem. My professor told me to load all my resources with the Try-with-resources block instead of using try/catch ( See code below ). I am using the Clip class from…
Towni0
  • 87
  • 1
  • 6