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

Multichannel USB recording with Java Sound API?

I'm trying to record/process some audio from three usb microphones with Java Sound on Snow Leopard (but can switch to Windows if it fixes things). Problem is, when I try to use the mixer that corresponds to the usb mic, Java Sound tells me that the…
Tom
  • 593
  • 4
  • 6
34
votes
1 answer

Reading MIDI files in Java

I'm trying to read in .MID files to a Java program, and would like to separate each note/chord so as to display them on a UI of some sort. I didn't have much luck using the Sequencer API in Java, and trying to use MidiFileReader directly didn't work…
Hassan Khan
  • 766
  • 3
  • 9
  • 21
24
votes
3 answers

Audio volume control (increase or decrease) in Java

How do I increase the volume of an outgoing wav audio stream using Java? I'm having issues with various Java TTS engines and the output volume of the synthesized speech. Is there an API call or a doo-hickey.jar I can use to pump up the volume?
Cliff
  • 10,586
  • 7
  • 61
  • 102
20
votes
4 answers

Convert Midi Note Numbers To Name and Octave

Does anybody know of anything that exists in the Java world to map midi note numbers to specific note names and octave numbers. For example, see the reference table: http://www.harmony-central.com/MIDI/Doc/table2.html I want to map a midi note…
Jonathan Holloway
  • 62,090
  • 32
  • 125
  • 150
20
votes
2 answers

Detect silence when recording

How can I detect silence when recording operation is started in Java? What is PCM data? How can I calculate PCM data in Java? I found the solution : package bemukan.voiceRecognition.speechToText; import javax.sound.sampled.*; import…
olyanren
  • 1,448
  • 4
  • 24
  • 42
20
votes
2 answers

How do I use audio sample data from Java Sound?

This question is usually asked as a part of another question but it turns out that the answer is long. I've decided to answer it here so I can link to it elsewhere. Although I'm not aware of a way that Java can produce audio samples for us at this…
Radiodef
  • 37,180
  • 14
  • 90
  • 125
19
votes
3 answers

frame rate vs sample rate

What is the difference between sample rate and frame rate? I tried to check a song and found sample rate and frame rate using java.They have same value, It makes me confuse. doesn't frame consist of many sample? thank you
wendy0402
  • 495
  • 2
  • 5
  • 16
17
votes
1 answer

Where can I download the mp3plugin.jar to play MP3s in Java code?

I need to Play a MP3 File in Java code under Linux environment (Ubuntu 11.04). I tried to download the MP3plugin.jar file from http://www.oracle.com/technetwork/java/javase/download-137625.html ,but I can't see it in the list. Note : "I downloaded…
Reem
  • 173
  • 1
  • 1
  • 4
17
votes
4 answers

Join two WAV files from Java?

What's the simplest way to concatenate two WAV files in Java 1.6? (Equal frequency and all, nothing fancy.) (This is probably sooo simple, but my Google-fu seems weak on this subject today.)
krosenvold
  • 75,535
  • 32
  • 152
  • 208
16
votes
2 answers

How do I know if I'm on the event dispatch thread?

1.Consider my code is on some line of a JPanel that I have, am I automatically on EDT? 2.Same question for all other classes which are not belong to GUI, JPanels or other view classes, simple logical class. 3.If I have JPanel which I'm playing…
JavaSa
  • 5,813
  • 16
  • 71
  • 121
16
votes
3 answers

Java audio visualizer- How to capture real-time sound output to speaker?

tl;dr For future readers, recording real-time audio is not possible (for now) with Java or C#. Use C++, as it provides a plethora of audio api's. My goal is to get the current sound played on a Windows machine, and analyze the sound much like a…
Eric
  • 444
  • 7
  • 19
16
votes
2 answers

Java beep sound: Produce sound of some specific frequencies

I was experimenting with producing beep using Java. I found this answer on SO. I am using the code from that answer to produce beeps. The code is: import javax.sound.sampled.*; public class Sound { public static float SAMPLE_RATE = 8000f; …
dryairship
  • 6,022
  • 4
  • 28
  • 54
16
votes
2 answers

MIDI beginner - need to play one note

I don't know very much about Java's MIDI function. In fact, it utterly bewilders me. what I'd like to do however is just build a simple application that will play one note. How to play a single MIDI note using Java Sound? The support for this out…
user2366366
  • 161
  • 1
  • 1
  • 3
15
votes
7 answers

Sine Wave Sound Generator in Java

What's the simplest way to generate a sine wave sound at any frequency in Java? A sample size more than 2 bytes would help, but it doesn't really matter.
milo
  • 555
  • 2
  • 7
  • 13
15
votes
4 answers

Audio: Change Volume of samples in byte array

I'm reading a wav-file to a byte array using this method (shown below). Now that I have it stored inside my byte array, I want to change the sounds volume. private byte[] getAudioFileData(final String filePath) { byte[] data = null; try { …
Macks
  • 1,696
  • 5
  • 23
  • 38
1
2 3
61 62