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

Java getting input from MIDI keyboard

I have designed my own synthesizer in java and I now want to connect it with a midi keyboard. My class below searches through all the midi devices that have transmitters. It successfully finds my midi keyboard. I add my own receivers to each…
Jonathan
  • 1,256
  • 4
  • 12
  • 18
12
votes
3 answers

Capturing speaker output in Java

Using Java is it possible to capture the speaker output? This output is not being generated by my program but rather by other running applications. Can this be done with Java or will I need to resort to C/C++?
dbotha
  • 1,501
  • 4
  • 20
  • 38
10
votes
1 answer

Trouble playing wav in Java

I'm trying to play a PCM_UNSIGNED 11025.0 Hz, 8 bit, mono, 1 bytes/frame file as described here (1) and here(2). The first approach works, but I don't want to depend on sun.* stuff. The second results in just some leading frames being played, that…
yanchenko
  • 56,576
  • 33
  • 147
  • 165
10
votes
6 answers

how can I wait for a java sound clip to finish playing back?

I am using the following code to play a sound file using the java sound API. Clip clip = AudioSystem.getClip(); AudioInputStream inputStream = AudioSystem.getAudioInputStream(stream); clip.open(inputStream); clip.start(); The method…
Panagiotis Korros
  • 10,840
  • 12
  • 41
  • 43
10
votes
3 answers

Extract human sound from a wav file using java

I am working on a project where I have to extract the human sound from a audio .wav file using java. The audio .wav file may have 3 to 4 sounds like dog, cat, music and human. I will have to identify the human sound then exatract that part from the…
Muhammad Ijaz
  • 181
  • 1
  • 4
  • 15
10
votes
1 answer

Do I need to care about big endian and little endian when I read data through AudioInputStream?

I am reading a wav file through AudioInputStream into a byte array, AudioInputStream audiofile = AudioSystem.getAudioInputStream(f); byte[] audio=new byte[numberofframes*framesize]; int bytes=audiofile.read(audio); do I need to arrange…
10
votes
3 answers

How can I draw sound data from my wav file?

First off this is for homework or... project. I'm having trouble understanding the idea behind how to draw the sound data waves on to a graph in Java for a project. I have to make this assignment entirely from scratch with a UI and everything so…
Kevin Heng
  • 173
  • 1
  • 3
  • 10
9
votes
3 answers

Audio Clip won't loop continuously

Can anyone point me in the right direction as to why this code will not play this audio clip continuously? It plays it once and stops. final Clip clip = AudioSystem.getClip(); final AudioInputStream inputStream = AudioSystem.getAudioInputStream(new…
daveed007
  • 168
  • 1
  • 1
  • 7
9
votes
2 answers

MIDI instrument listing?

I have recently implemented a MIDI Beatbox from the code in Head First Java and would really like to do more with Java's MIDI capabilities. I thought that I might start by adding more, non-percussive instruments to the existing code, but I cannot…
cornbread ninja
  • 417
  • 1
  • 6
  • 17
9
votes
3 answers

FreeTTS no audio linux ubuntu - no errors

I am running Ubuntu 10.10 using Java 6 and can not get FreeTTS to output any audio. I have tried it now on 3 different computers and even asked a buddy of mine to try it on his Ubuntu PC and he had the same problem. There is absolutly no errors that…
John
  • 236
  • 1
  • 4
  • 11
9
votes
4 answers

Acoustic echo cancellation in Java

I'm implementing a VOIP application that uses pure Java. There is an echo problem that occurs when users do not use headsets (mostly on laptops with built-in microphones). What currently happens The nuts and bolts of the VOIP application is just the…
Garg Unzola
  • 376
  • 1
  • 4
  • 9
9
votes
1 answer

How to get Audio for encoding using Xuggler

I'm writing an application that records the screen and audio. While the screen recording works perfectly, I'm having difficulty in getting the raw audio using the JDK libraries. Here's the code: try { // Now, we're going to loop …
wrahool
  • 1,101
  • 4
  • 18
  • 42
9
votes
5 answers

Convert audio stream to WAV byte array in Java without temp file

Given an InputStream called in which contains audio data in a compressed format (such as MP3 or OGG), I wish to create a byte array containing a WAV conversion of the input data. Unfortunately, if you try to do this, JavaSound hands you the…
Robert J. Walker
  • 10,027
  • 5
  • 46
  • 65
9
votes
6 answers

Can Java Sound be used to control the system volume?

Java Sound offers FloatControl instances for various sound line functionality, and both a MASTER_GAIN & VOLUME control type. Can these controls be used to change the system volume?
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
8
votes
2 answers

Java raw audio output

Just wondering if there is a library in Java like the module PyAudiere in Python, that simply allows you to create tones and play them, like this sample Python code: device = audiere.open_device() tone = device.create_tone(500) #create a 500hz…
sbrichards
  • 2,169
  • 2
  • 19
  • 32
1
2
3
61 62