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
8
votes
3 answers

How can i remove background noise with java, while recording audio in a crowd zone?

When i capture with JavaSound or Third party sound capture tools and record it to a file. Afterwards read the file back to modify it, is there any way to remove the "background noise" with my java application. Such as road traffic/air noises while…
user285594
8
votes
2 answers

Understanding the constructor of AudioFormat , AudioInputStream and start method

I have tried writing program that plays a sound file but have been unsuccessful so far. I am unable to understand some parts of the code: InputStream is = new FileInputStream("sound file"); AudioFormat af = new AudioFormat(float sampleRate, int…
Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328
8
votes
2 answers

How to develop screen capture to video application

I visited a web site screencast-o-matic. They have a web-application of java applet which capture screen to export as video. I want to develop similar application. What are the knowledge and steps required to do it? another website: screenr.
Tapas Bose
  • 28,796
  • 74
  • 215
  • 331
8
votes
19 answers

What output and recording ports does the Java Sound API find on your computer?

I'm working with the Java Sound API, and it turns out if I want to adjust recording volumes I need to model the hardware that the OS exposes to Java. Turns out there's a lot of variety in what's presented. Because of this I'm humbly asking that…
Dave Carpeneto
  • 1,042
  • 2
  • 12
  • 23
8
votes
1 answer

Java Sound: Getting default microphone port

Using Java, I'm trying to record sound from the default microphone and show the current volume and mute status (as set at OS level, not interested in checking bytes if possible). So far, I can get the TargetDataLine and record to it using the…
laurentius
  • 1,093
  • 1
  • 9
  • 20
8
votes
4 answers

How to sample multi-channel sound input in Java

I realised this might be relatively niche, but maybe that's why this is good to ask anyway. I'm looking at a hardware multiple input recording console (such as the Alesis IO 26) to take in an Adat lightpipe 8 channel input to do signal processing.…
johncch
  • 352
  • 3
  • 11
8
votes
1 answer

TarsosDSP Pitch Analysis for Dummies

I am woking on a progarm that analyze the pitch of a sound file. I came across a very good API called "TarsosDSP" which offers various pitch analysis. However I am experiencing a lot of trouble setting it up. Can someone show me some quick pointers…
user4835582
8
votes
2 answers

How to calculate the level/amplitude/db of audio signal in java?

I want to create a audio level meter in java for the microphone to check how loud the input is. It should look like the one of the OS. I'm not asking about the gui. It is just about calculating the audio level out of the bytestream produced by n =…
AliceInChains
  • 167
  • 1
  • 1
  • 9
8
votes
2 answers

Converting the sample rate on-the-fly when reading a WAV file into a samples array with Java

I've got a collection of short WAV files that I would like to process in Java using various digital signal processing algorithms. I need to get an array of int valued samples for this purpose, encoded at the 11025 Hz frame rate. The source files…
pako
  • 1,908
  • 4
  • 24
  • 40
8
votes
2 answers

Any supported sound formats for Java on Windows 7?

We'll, I've been beating my head against a wall trying to get Java to play some simple wav files without any luck. I've tried this code: Clip clip = AudioSystem.getClip(); AudioInputStream inputStream = AudioSystem.getAudioInputStream(new…
8
votes
2 answers

mp3 to wav conversion in java

My code to convert mp3 to wav is: package audio1; import java.io.File; import javax.sound.sampled.AudioFileFormat; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; public…
nullptr
  • 3,320
  • 7
  • 35
  • 68
7
votes
7 answers

Playing MP3 using Java Sound API

Can you please suggest that how can i write a piece that plays a song.? I tried the following snippet but i get the this exception: import sun.audio.*; import java.io.*; class tester { public static void main(String args[]) throws Exception { …
Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328
7
votes
1 answer

Could not get audio input stream from input stream

I want to get the sound file at the URL provided in the code and play it (It is in mp3 format). I looked through some Stack Overflow questions related to this problem, and they all said to get mp3plugin.jar so I did. In Eclipse, I added it as an…
Encoded Lua
  • 93
  • 1
  • 10
7
votes
1 answer

Simulate microphone Input

I am trying to write a little program that reads a wav file and sends the output as if it would come from my microphone. Unfortunately I do not have much experience with the sound API. Background: What I am basically trying to realize is a program…
Moh-Aw
  • 2,976
  • 2
  • 30
  • 44
7
votes
3 answers

Weak references and `OutOfMemoryError`s

I have a SoundManager class for easy sound management. Essentially: public class SoundManager { public static class Sound { private Clip clip; // for internal use public void stop() {...} public void start() {...} …
wchargin
  • 15,589
  • 12
  • 71
  • 110
1 2
3
61 62