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

Loop audio files using .wav format in java

i am trying to loop an audio file but when i've tried the other various methods available, my music doesn't play. My basic code is: import java.io.*; import sun.audio.*; public class PlayMusic { public void playSound() { try { …
0
votes
1 answer

Changing system volume using JLGui

I am currently learning how to build a simple MP3 player with jlgui (using swt to control it). While i am getting along nicely there is one thing which is really throwing me and that is controlling the volume and pan of the sound coming out of the…
Robert Flook
  • 307
  • 6
  • 12
0
votes
0 answers

.getSourceLines() always returns 0

I have a mixer and I want to gather information on its source lines. My code is as follows. myMixer = AudioSystem.getMixer(mixerInfo[i]); // index through all list of mixers Line[] lines =…
Dr.Knowitall
  • 10,080
  • 23
  • 82
  • 133
0
votes
2 answers

Cannot play embedded sound in a jar file

I am creating a software for personal use titled BatteryBeeper. It will remind me to charge the laptop when the charge is whatever I set to be reminded at. It is supposed to play a sound when the charge hits the set threshold. I had a look at…
An SO User
  • 24,612
  • 35
  • 133
  • 221
0
votes
0 answers

How can I enable fedora to let my Java program access audio device

I have a problem where I'm trying to access the audio device that lets me listen in from the microphone jack. This code works under Windows with the output, Mic is supported! Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo(); Mixer…
Dr.Knowitall
  • 10,080
  • 23
  • 82
  • 133
0
votes
1 answer

Java game sound effects isn't working correctly

I'm trying to do my school project (a simple Java game) and I cant's get the sound effects work. I'm doing it using Clip and now my playSound-method looks like this: public void playSound(File filename) { try { AudioInputStream sound =…
0
votes
0 answers

Using AudioInputStream with a ProgressMonitorInputStream

Revised/Summary: I'm using a plugin to decode an MP3 audio file. I'd like to provide a ProgressMonitor to provide feedback to the user. The logic of constructing an AudioInputStream that decodes the MP3 format AudioFile is as…
ags
  • 719
  • 7
  • 23
0
votes
1 answer

How to draw a waveform for 2 or more channels:Getting amplitude from 2 or more channels?

I am doing a project which requires signal processing of the audio when a wave file is provided to me. I know how to compute the amplitude using sample value of a channel using the formula 20*log(Sample Value/Maximum attainable sample Value) But…
Soul Enrapturer
  • 367
  • 2
  • 3
  • 14
0
votes
1 answer

How to play mp3 file in a loop, with pause and restart option in java?

Possible Duplicate: Music Loop in Java Currently I am using this code to play a mp3 file public void run(String url) { try { ContinuousAudioDataStream loop = null; InputStream in; in =…
Tushar Monirul
  • 4,944
  • 9
  • 39
  • 49
0
votes
3 answers

music player "file not found" exception?

I'm try to add a soundtrack to a simple little java game, and I've researched how to do it to the extent that I have code that compiles. However, when I run it, I get a FileNotFound exception. I'm using Eclipse and my wav file is in the same…
dhsmith
  • 250
  • 1
  • 2
  • 11
0
votes
3 answers

Java Synth: Making a Test Tone

I've been looking at people's Java synth but can't make out how to produce a simple version of their program. My goal is to create a simple test tone in java, which the user will be able to alter by pressing certain keys. For example pressing "r"…
Fred V
  • 187
  • 1
  • 11
0
votes
3 answers

Add sound to a countdown

How to add sound to a countdown? timer = new Timer(); timer.schedule(new CountdownTask(), seconds*1000); Later in the program this code will activate and the timer will begin. Is there any way to make a sound file play during the countdown that…
0
votes
0 answers

Java Change Another Applications' Sound

I am now interested in changing volume of my system. I am running on Windows 8 and I found several of codes that can change "java application's" volume only. But I want to change not only my applications volume but also system's volume. I used this…
OBEN ISIK
  • 55
  • 7
0
votes
2 answers

AudioInputSream gives nullPointerException

I am trying to make a music player in java. I have gone to numerous websites and looked at resources to see how it works, but AudioInputStream gives me a nullPointerException in a place where I least expect it! It seems that no one has asked this…
Ashok
  • 134
  • 13
0
votes
1 answer

How to play a wav file with no lag?

I've looked around the internet on ways to play wav files, but I have found that they do not play on a separate thread and so cause the program to halt until the song is done, which does not work for a game. However, when I try to play everything on…
Octavia Togami
  • 4,186
  • 4
  • 31
  • 49