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

Is there a Java library to programmatically remove parts of an .mp3 audio file?

I am working on programmatically removing/redacting parts of an .mp3 audio file. An example scenario is to mute/ remove the audio from 1:00 - 2:00 in a 3 minute (0:00 - 3:00) audio file. Do we have any libraries that can be useful for this…
-1
votes
1 answer

Audio not playing in Java swing

I am trying to get a button to play audio when pressed matching to a value. This is what i have got so far but it isnt working. I followed this tutorial: https://www.youtube.com/watch?v=3q4f6I5zi2w&list=PLrqwM2iFaguigFGMfG4f4H516zVByp97N but as it…
jlewn01
  • 15
  • 4
-1
votes
1 answer

Extract gain of audio using java

I am trying to know the gain / decibels and other possible parameters from wav audio file. But Clip.getLevel() method is always returning gain in -0.1 value. public void prepareAudio() { try { Line.Info linfo = new…
-1
votes
1 answer

Java Sound API. Getting supported audio formats from mixer

I'm trying to get a line from an external mixer connected to my pc via USB. So I wrote a simple program to list all the mixers and their respective source lines (outputs) and target lines (inputs), and it works properly: import…
Sarrio
  • 151
  • 2
  • 8
-1
votes
1 answer

Mac only displays "Default Audio Device" when querying mixers

When I query all the mixers on my Macintosh (MacPro 13inch; 10.13.1), all that shows up is 6 iterations of "Default Audio Device, version Unknown Version". I am simply wondering why this is, and how I might be able to fix it. If it matters, I am…
avghdev
  • 89
  • 8
-1
votes
1 answer

Listening for the end of a song - jukebox

I am making a jukebox program to run independently on a raspberry pi using netbeans. I'm trying to write a method that allows for the music to switch after it has finished playing. I know how to create a listener, but I need to still have the…
-1
votes
2 answers

How do I pause/stop a song that's being played?

I have created a program where I can play a song, However I cannot get it to pause/stop and when I click the play button again the song loops over and over again. How can i get the song to pause or stop? Here's my source code below to play a…
-1
votes
1 answer

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException on mouse move

I want to create a game and when I move the mouse to a button I want to play back a sound. This is the JFrame class: package jatek; public class jatek extends javax.swing.JFrame { public jatek() { initComponents(); …
-1
votes
2 answers

AudioClip volume problems

I watched a great tutorial of Mattew on how to implement audio sounds in Java games. The problem is that even after I decreased the volume of the wav file when I run the game the volume of the wav sound file is still very high in Java, I mean you…
stefanbanu
  • 53
  • 1
  • 10
-1
votes
1 answer

Pausing of the first playing wav file when second wav file is triggered. How to?

I have here a code which listens to the input of the user. System.out.println(message);{ if(message.equals("play")){ try { AudioInputStream inputStream = AudioSystem.getAudioInputStream(new…
Kerv
  • 179
  • 1
  • 5
  • 15
-1
votes
2 answers

Smooth sound seek

I have a not so simple question about Java Sound ( javax.sound package ). I am implementing MP3 player with cross fade and smooth volume and seek controls. I am reading sound as stream in 4096byte chunks and calculate the position in miliseconds…
Jan Cajthaml
  • 403
  • 3
  • 13
-1
votes
2 answers

Sounds won't play in java.. JFrame and Canvas not Applet

I'm currently working on my first game in java and i'm trying to implement sounds when the spaceship is getting hit.. this is my code . I get a null pointer exception but my sound is in the right place "workspace/project/src/sounds/" public class…
-1
votes
1 answer

Java sound class not looping

I'm trying to develop a game and I've found 2 sources for sound. I posted the whole class below, it won't seem to loop even when looped_forever or loop_times is setup to do so: package com.jayitinc.ponygame; import java.io.*; import…
-1
votes
3 answers

How to play a WAV in Java, when the WAV is contained inside the JAR

I've been trying to deal with sound on my Applet for a bit now, and Instead of trying all the different methods, what is the best way to play Sound in Java? There are a few requirements: Needs to be able to loop Needs to be able to load a WAV from…
Jeremy Sayers
  • 637
  • 4
  • 10
  • 23
-2
votes
2 answers

How to play 2 audio simultaneously in java?

Basic idea is to combine images, voice and background music to create a single movie. I am able to do the same with images and voice audio (single audio) but now i want to add 2 audio files for the same. Please help.
user723282
  • 15
  • 3
1 2 3
61
62