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

Best addon for reading data from .mp3 with JDK 1.6

I'm attempting to write a music visualizer. I've looked into it and sound.sampled looks like a good library for reading the data. However, the jdk can only load .wav files. So I'm looking for a flexible addon that'll enable me to load .mp3. The…
Perry Monschau
  • 883
  • 8
  • 22
3
votes
2 answers

Java Exception Reading Stream from Resource .wav

I guess my code is okay, and my .jar file its okay with the .wav inside it.. But when I try to load it using getResourceAsStream I get a error.. this is my error: java.io.IOException: mark/reset not supported at…
TiagoM
  • 187
  • 3
  • 14
3
votes
1 answer

Popping/Crackling When Using a Java Source Data Line for Audio

I am having a problem with a Java Source Data Line. I need to play a tone, so I've created a Tone class that just represents a tone. Everything works fine, except that when I play the sound, the speakers pop at the beginning of the sound. Is there…
David Watson
  • 2,031
  • 2
  • 13
  • 17
3
votes
1 answer

How can I write the contents of a SourceDataLine to a file?

I am modifying an application that plays audio data to write the data to a file instead. As it is currently implemented, a byte array is filled dynamically, and the contents of this buffer are written to a SourceDataLine each time it is filled. I…
Travis Christian
  • 2,412
  • 2
  • 24
  • 41
3
votes
0 answers

Weird java sound glitch in eclipse

I'm using javax's midi classes to play a MIDI in the background of my program. When I compile in Eclipse, the MIDI plays fine but there is some sort of weird echoing feedback noise which is almost as loud as the MIDI itself. My code: public class…
3
votes
1 answer

AudioClip trouble

I am getting an Expected Identifier error when trying to compile an applet with AudioClip. I plan on adding this to a JFrame, and I was hoping to get the AudioClip to loop. import java.applet.*; import java.awt.*; public class Audio extends…
TEddyBEaR
  • 137
  • 1
  • 9
3
votes
3 answers

Java audio input inconsistencies

I've been working on a guitar tuner Java application for quite some time and have finally managed to get the pitch (fundamental frequency) detection to accurately determine the fundamental frequency of the input using an FFT and the Harmonic Product…
nihilo90
  • 109
  • 1
  • 9
3
votes
4 answers

mixing two audio file using mixer

how can i mix two audio files into one file so that the resultant file can play two files simultaneously? please help.. here what i am doing is that i am taking two files and concat them into another file.. but i want the file to be played…
pal sarkar
  • 105
  • 1
  • 9
3
votes
2 answers

facing issue in loading a mp3 file in java getting could not get audio input stream from input file

I have the following code: String fileName="D:/downloads/song.mp3"; File soundFile = new File(fileName); AudioInputStream audioInputStream = null; try { audioInputStream = AudioSystem.getAudioInputStream(soundFile); } catch (Exception ex) { …
Rajesh Agrawal
  • 484
  • 2
  • 5
  • 18
3
votes
2 answers

obtaining an AudioInputStream upto some x bytes from the original (Cutting an Audio File)

How can i read an AudioInputStream upto a particular number of bytes/microsecond position ? For example : AudioInputStream ais = AudioSystem.getAudioInputStream( new File("file.wav") ); // let the file.wav be of y bytes Now i want to obtain an…
Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328
3
votes
3 answers

cutting a wave file

How can i cut a .wave file using java ? What i want is : when the user presses the button labeled cut it should cut the audio from the previous mark (in nanoseconds) to the current position in nanoseconds. (mark is positioned to the current…
program-o-steve
  • 2,630
  • 15
  • 48
  • 67
3
votes
1 answer

concatenate 2 byte arrays and then convert to an audio stream

The following is the code that reads audio data from 2 audio input streams into a byte array. import javax.sound.sampled.*; import java.io.*; class tester { public static void main(String args[]) throws IOException { try { Clip clip_1 =…
Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328
3
votes
1 answer

how to set MIDI sound pan?

Can anyone please suggest me how to set panning for a MIDI sound. I am using java MIDI synthesis and can make it sound. But I want the sound to pan from left to right speakers. I did google but it seemed not to clear to me much? Here the example of…
davidGame
  • 31
  • 3
3
votes
3 answers

why this code doesn't play the sound file

The code import javax.sound.sampled.*; import java.io.*; public class Tester { static Thread th; public static void main(String[] args) { startNewThread(); while( th.isAlive() == true) { System.out.println("sound thread is…
Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328
3
votes
1 answer

Play back sound in Kotlin/Java directly from generated sound array

I am looking for a way to generate and play back sound in Kotlin/Java. I have been searching a lot and tried different solutions, but it's not really satisfactory. I'm not looking for the Java Control class, that lets me add reverb to existing…
user1661303
  • 539
  • 1
  • 7
  • 20