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

Play sound on specific sound device java

I am trying to do something simple. I want to play sound on a given sound media instead of playing on the default one. There is my last try, to iterate thought all the media and play a sound. Only the media on the default device play something. Even…
Manticore
  • 441
  • 5
  • 24
4
votes
1 answer

How to buffer and play sound data from OGG files with Java Sound

I'm trying to use Java Sound (with MP3SPI and VorbisSPI) to read audio data from WAV, MP3 and OGG files, storing it into a byte array, in order to play it later from there. In order to do so, I use code like this: public Sound loadSound(File file){…
EPresident
  • 78
  • 1
  • 5
4
votes
2 answers

Clip plays WAV file with bad lag in Java

I've written a code that read a WAV file (size is about 80 mb) and plays that. The problem is that sound plays badly (extreme lags). Can you please tell me what's the problem? Here's my code: (I call the doPlay function inside a Jframe…
Alireza Farahani
  • 2,238
  • 3
  • 30
  • 54
4
votes
3 answers

Audio manipulation with Java

The smallest unit of a digital image is a pixel. What is the smallest unit of digital sound? what can be considered to be a pixel for sound? How can we use java to manipulate it?
user3177843
  • 65
  • 1
  • 7
4
votes
1 answer

Buzzing on Exit

I'm trying to build a game that uses sound effects. I haven't dealt with the Java API before so I may be making some mistakes. That said though, the effects work great — my only problem is that I get a strange buzzing sound for maybe a second…
Sinclair
  • 91
  • 7
4
votes
3 answers

Voice changer for audio files

I have some audio files in different voices (only spoken words there is no music or noise). I am aiming to change all that audios for a one standard voice "man" voice for example For example: Input : audio file say "Hello World" in Woman/man…
4
votes
1 answer

Caching sounds using byte arrays from within jar file

I can read and play sounds using the "Playing a Clip" solution from the javasound tag wiki page. However, for sounds that are played frequently (e.g., a quick laser gun sound, a footstep, etc.), it's jarring to me to be opening streams and…
wchargin
  • 15,589
  • 12
  • 71
  • 110
4
votes
3 answers

Best way to get Sound on Button Press for a Java Calculator?

I'm a learning Java student working on an independent project for my Resume. I decided to do a Java calculator because I know most of the components that make it up. One thing I don't know how to do is add sound on the button press. I have a vague…
4
votes
1 answer

Access to CD-ROM using Java

I would like to ask if there is any possibility to access the cdrom device via sound libraries in Java. What I want to do is to mute CD Analog. I've searched using google for a long time, but there is no information about such an operation. I assume…
rainbow
  • 1,161
  • 3
  • 14
  • 29
4
votes
2 answers

Turning the computer volume up/down with Java?

I want to turn the master volume of the computer up and down (100%/0%), with just a command. I saw that I could use FloatControl, but I'm not sure how to use it.
xR34P3Rx
  • 395
  • 9
  • 28
4
votes
1 answer

Looping a MIDI sequence in Java

I'm trying to loop a MIDI sequence in a java game I'm making and I'm having some issues. The current code I have does repeat the sequence, but there is a large delay between the end of the sequence and the restart. How can I eliminate this? Here's…
MichaelPlante
  • 452
  • 1
  • 4
  • 14
4
votes
5 answers

What audio format should I use for java?

I am making a Java based game for which I want to add some sound effects. I searched and found myself more confused. I know the coding differs from file format to format. I just need some sounds - does not matter which format. So please suggest me…
Sunil Shahi
  • 641
  • 2
  • 13
  • 31
4
votes
1 answer

Javasound not playing .m4a files through JAAD (an SPI)

I'm trying to play some .m4a files, and I understand that JAAD only supports decoding AAC, but there are songs that I am able to get the sourceDataLine from, and then when I go to try to play them, I get behavior like this: We read: 1024 bytes. We…
Nico
  • 1,181
  • 2
  • 17
  • 35
3
votes
1 answer

How to implement seek on mp3

I am about to get into a project that involves decoding + playing an mp3 stream. I have a Java decoder (JLayer), but as far as I can see it has no seek functionality (I don't use the built in player, I need to implement my own player). Also, the…
SirKnigget
  • 3,614
  • 2
  • 28
  • 61
3
votes
1 answer

Java Sound not very clear when streaming

Hi I've been writing a chat client and wanted to test the Java Sound API. I've managed to get sound working from the mic to the speakers on different computers via UDP. However the sound isn't very clear. To check whether this was because of lost…
MachoChild
  • 37
  • 7