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

Java/Linux: sound output on wrong card

I have a java application that replays some PCM sound on my linux box. Unfortunately it uses the wrong soundcard. I could direct xine by using the .asoundrc to the correct soundcard - but how can I tell the JVM which sound output to use by default?
Elmi
  • 5,899
  • 15
  • 72
  • 143
0
votes
2 answers

Clear cache for java application

i am trying to write a program that detects when the headphones are plugged into the system and then run another piece of code when you remove the headphones. The code is working fine but the problem that i am facing is that the status of the…
user1492955
  • 1,728
  • 2
  • 12
  • 13
0
votes
1 answer

Playing a Sound Effect in Java

I'm trying to do the equivalent of this line of code, except substituting a small mp3 file for the system beep: Toolkit.getDefaultToolkit().beep(); I have an mp3 file that has a little sound effect that I want to play. Is this a relatively easy…
AndroidDev
  • 20,466
  • 42
  • 148
  • 239
0
votes
1 answer

Audio waveform in java finished coding but readings are different for waveform

I have captured audio from mic and drawn a waveform of the recording, my doubt is will the waveform readings will be between -1+1 or +5-5 ?? my readings are between like 1000's.. could some one help?? Using code from internet…
rsenthilk
  • 95
  • 1
  • 7
0
votes
1 answer

NullPointer when playing sound on Java

I'm getting an error when trying to play sound. I'm getting a null pointer exception for some reason. The location and file I'm using both exsist, and when outputting the file string I do get the correct path to the file. The nullpointer is on the…
ComputerLocus
  • 3,448
  • 10
  • 47
  • 96
0
votes
0 answers

Synthesizing sound while midi recording using a midi instrument

I'm making a Java application to record midi using a midi instrument. Ive been using Java with an ASIO driver using the proyect JAsioHost to avoid latency. Currently I'm producing pure sine waves for each note. I would like to produce sound using…
Camilo Barraza
  • 195
  • 1
  • 9
0
votes
1 answer

How do I correctly use FloatControl with the Java Sound API?

I am currently writing a test program in Java that I want to be able to control my computer's main SPEAKER with a JSlider on a GUI application. I have read through this page on the AudioSystem class and this page on Controls. It is my understanding…
Eric after dark
  • 1,768
  • 4
  • 31
  • 79
0
votes
1 answer

Streaming Radio mp3 java

I'm trying to do a simple mp3 player,everything is perfect, just I have one problem I can't do (Play) the streaming radio mp3, where i do button 'play' i get this message: Unable to handle format: mpeglayer3, 44100.0 Hz, 16-bit, Stereo,…
cleo
  • 165
  • 1
  • 11
0
votes
1 answer

flat zeros being output every sample when trying to get data from a microphone

I am making a Vocoder in java built into a synthesizer built based on a tutorial from Dr. Dobb's and whenever i try to get samples from the microphone it just returns zeros for the samples even when there is mic input. This is the settings of the…
ILOVEPIE
  • 177
  • 1
  • 10
0
votes
1 answer

Exception not raised while opening TargetDataLine

According to Javadocs, when I used javax.sound.sampledTargetDataLine's following method: public void open(AudioFormat format,int bufferSize) Which says: Invoking this method with a requested buffer size that does not meet this requirement may…
abc
  • 315
  • 2
  • 5
  • 12
0
votes
1 answer

Stream audio from URL in java Swing App

I want to play streaming audio from server in java swing app. There's a public live stream available at http://64.202.98.32:6210. I have tried the java sound API without success: URL ur= new URL("http://64.202.98.32:6210"); AudioStream as = new…
Asghar
  • 2,336
  • 8
  • 46
  • 79
0
votes
1 answer

How do I control the volume of my PC speakers with a JSlider?

I'm currently writing a program in Java that I would like to use to control my PC's main speakers with. At the moment I am trying to use a JSlider. Is there a way that I can use ChangeListener to do this? If not ChangeListener, is there another way…
Eric after dark
  • 1,768
  • 4
  • 31
  • 79
0
votes
1 answer

Java MP3 Waveform Normalization

I have been trying to generate Audacity-like waveforms. I used java sound api and got up to a decent point of representing the actual mp3 to a waveform. Do you have in mind any mathematic function that I can apply to the dataset to be painted so the…
Potney Switters
  • 2,902
  • 4
  • 33
  • 51
0
votes
3 answers

Java midi inconsistent playback quality

I've recently run into a strange bug with playing midis in a game I'm developing. I thought my midi code was working fine since it used to play midis without sounding weird. Now whenever it plays midis, they sound all tinny, echo-y, and loud. I…
Cazra
  • 143
  • 10
0
votes
1 answer

read midi IO device with java

I am trying to parse the input from a midi device connected to my laptop. So I want to locate the device, connect to it and receive the input from it. I started with select midi device in java, but I am having some trouble getting my way around…
Potney Switters
  • 2,902
  • 4
  • 33
  • 51