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

Java Audio Streaming isn't Working, keep running into an error

I'm following this Java tutorial, and I've come across how to play audio, I followed the exact steps to writing the code, however, despite this, I get an error message, I doubt the video is out of date considering it's only a month old, so I'm not…
-2
votes
1 answer

How to use sound effects in Java 8? Snake eats apple

I wrote Snake code, and want to add a sound effect when snake eats an apple. I copyied a code from some guy on YT, but it doesn't work to me. Can somebody explain me how to do this? Code: import com.sun.tools.javac.Main; import…
Greedus
  • 1
  • 4
-2
votes
1 answer

sawtooth generator wave simple. java

i'm trying to make the simplest code (less than 3 or 4 lines) to generate a sawtooth wave in java I already know the period,frequency, and amplitude of the graph (2). Any suggestions appreciated. I know that i need to use mod arithmetic with the…
skar
  • 1
  • 1
-2
votes
1 answer

Stopping a clip from playing with a mute button?

I've been trying to create a functioning mute button in swing. On start up a clip plays in my application. There is a button that (is supposed) to allow the user to stop the music. What am I doing wrong? This is the code from my main method. try { …
NemoLKLK
  • 35
  • 5
-2
votes
2 answers

Could not play a sound in swing

I am trying to play a .wav file everytime I press a button. I've put the resource in the workspace, together with my project. Is that wrong? I get this error message: javax.sound.sampled.AudioInputStream@341bdd4c …
Kharbora
  • 129
  • 1
  • 8
-2
votes
1 answer

Java clip not working

Can someone please help me understand why this code below doesn't work? I start the clip by calling method start(). This method creates a new thread for the clip to run. However, no it doesn't seem to play anything. The code is compiled without any…
Crazed Hermit
  • 11
  • 1
  • 3
-2
votes
1 answer

Can I create AudioInputStream from compressed audio byte array?

I am new to Audio technology. I am trying to create AudioInputStream from compressed Audio Byte array, but its not working as expected, its returning 0's only.
Rajj
  • 101
  • 7
-2
votes
2 answers

How can i add background music to my program?

I am attempting to add background music to my program but when i specify the path to the audio file i get the error message. How else can I specify this(this is going to be sent to another person). So the path cannot be on my system, it must be…
-2
votes
2 answers

Create "sound bars" similar to the bars in windows mediaplayer

I have no idea what these bars represent, but still I want to make them in my app on Android platform. I want that the bars to change on a sound or in my case a recorded sample play. For…
eli
  • 490
  • 1
  • 3
  • 22
-3
votes
1 answer

How to convert audio string back to audio bytes in java

Bytes of recorded audio was sent together with HTTP request body. When the request is received on the server side, the audio data looks like…
Random Forkson
  • 71
  • 3
  • 17
-3
votes
2 answers

How to find a note's length in frames, bytes, and ints from its length in milliseconds

I need to make a function in Java that adds a note of a certain frequency and length to audio. I have the frequency as a double, and the note length in milliseconds. Full Function Description: This method takes one AudioInputStream and adds the…
Markeazy
  • 76
  • 10
-4
votes
1 answer

How can i create a class that has a function takes in a string input as filename and then plays a soundfile?

This code checks if the goblin is in the same position as a coin and then gives it points. It should also play a sound when a coin is picked up if (goblin.getPos().equals(coin.getPos())) { if (goblinTarget == coin) { …
monkey
  • 7
  • 1
-4
votes
1 answer

Code refactoring, but how?

I am reading a data from .wav file and then converting it into binary format. and then I write those binaries and create a new .wav file. I want that after getting binary format of .wav file I should do little modifications in its LSB's and then…
-6
votes
1 answer

Need a little with an audio player in java

I'm making an audio player in java,a small code snippet that runs .wav files is: AudioInputStream ais = AudioSystem.getAudioInputStream(new File("C:\\path\\c4.wav").getAbsoluteFile()); Clip clip = AudioSystem.getClip(); clip.open(ais); …
Sabre.Tooth
  • 189
  • 1
  • 3
  • 10
1 2 3
61
62