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

Trying to get audioInputStream of an audio file

//I am trying to concatenate a list of mp3 files using java. But when I am running the code I am getting the following error: //javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file …
Nick Div
  • 5,338
  • 12
  • 65
  • 127
0
votes
0 answers

How to play .3gp audio file in console?

I have to play a 3gp audio file present in my PC via a Java console program. I am not using applet... or Swing only console. How to play .3gp audio file in console?
Mr_Hmp
  • 2,474
  • 2
  • 35
  • 53
0
votes
1 answer

Playing MP3 files using pure Java

Is it possible at all to play MP3 files using only the built-in libraries provided with JDK. I've heard of the javax.media library which is found is 1.7 I think. By the way I know of jlayer but I don't want to use it.
temelm
  • 826
  • 4
  • 15
  • 34
0
votes
1 answer

Applet sound recorder

I have an applet which is doing some sound recording work. When I run it on eclipse with Applet viewer , the sound recording and its play back is working fine. But when I put that applet in browser, all the buttons and controls are visible but the…
Muhammad Salman Farooq
  • 1,325
  • 9
  • 26
  • 54
0
votes
2 answers

Transfer and extract message by Audio signal in Android

I do research about audio processing and have a big problem to solve. Is it possible to transfer a text message or binary stream(10101010) by embedding it into audio signal, broadcasting it so that other android devices can record that sound and…
0
votes
2 answers

Need help in building Android version of javax.sampled. AudioInputStream

Since Android doesnt support javax.sampled sound apis am trying to build AudioInputStream and Audioformat for WAV FILE. I tried to build a WAVE FILE class by reading the WAV file using this https://ccrma.stanford.edu/courses/422/projects/WaveFormat/…
rana
  • 1,824
  • 3
  • 21
  • 36
0
votes
1 answer

How to preload sound and play it in Java simply?

How to preload sound an play it in java from time to time? I found example including Clip.open(AudioInputStream) method but nowadays API has no one. I know I can open AudioInputStream and SourceDataLine and copy data from one to other but is there…
Suzan Cioc
  • 29,281
  • 63
  • 213
  • 385
0
votes
1 answer

Stopping a .wav

I have code that plays sound from a .wav file, but I have no way of stopping the song, or even quitting the program until it ends. As this is a 5 minute song, this is a problem. Here is the code for how I play the wav: public class EasySound{ …
dawsonc
  • 25
  • 3
0
votes
2 answers

WAV to MP3 - Java lib example

is there any example on how to use LameOnJ, Pure Java Mp3 Encoder etc. to encode WAV format to MP3 in java? Example code, tutorial anything would be great! I'm fully confused in libraries right now; tried Tritonus lib but it gave me: Error:…
Zaur Guliyev
  • 4,254
  • 7
  • 28
  • 44
0
votes
1 answer

Play frequencies of sound in Java dos style

In Turbo C++ we have a header file called dos.h which exposes three functions sound, nosound and delay. Using these three functions it was possible to write a rudimentary piano program in C++. I wanted to achieve the same result using Java. My…
Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
0
votes
1 answer

Creating a single sine wave within specified range

I am trying to imitate a string instrument. I have a ring buffer implemented as a Linked List with all of the values initialized at 0 to represent a sine wave at rest. I am writing a pluck() method that replaces the N elements(all values currently…
user1349933
  • 11
  • 1
  • 2
0
votes
1 answer

Playing a Sound Effect (mp3)

Does anyone know how to play an mp3 file in Java? I have a little sound effect that I want to play. Here's what I have import java.io.*; import java.media.*; File mp3Correct; Player correct; /* Load mp3 files */ mp3Correct = new File…
AndroidDev
  • 20,466
  • 42
  • 148
  • 239
0
votes
1 answer

Decoded mp3 stream can not be read

I am developing an application that uses mp3 encoding/decoding. While in principle it behaves correctly for most of the files, there are some exceptions. I detected that these files have a missing header. I get an array out of bound exception when…
Potney Switters
  • 2,902
  • 4
  • 33
  • 51
0
votes
1 answer

How do I make this sound loop?

I am trying to loop the sound in this code. In the finally block of the main try and catch I do this : if (loop) { auline.flush(); run(); } else { ended=true; auline.drain(); auline.close(); } but…
Trixmix
  • 81
  • 9
0
votes
3 answers

Fade music into new track?

I've started to make a basic game in Java just as something to do. Its all been going well, I have maps loading, drawing works fine etc. I have it playing music for the maps and sound effects for stuff like collision. However I feel like the music…
Ryuk
  • 95
  • 1
  • 5
  • 16