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
2 answers

Play an online audio file in Java

I am trying to play an online audio file in Java Here's a link to the file and this can be run from Java code. How can I play this from my Java code without downloading it to my PC?
user1226162
  • 1,972
  • 8
  • 27
  • 42
0
votes
5 answers

how do i make music play when i open a GUI

So i want to get a game that i'm making to start playing music when i open it. i have never done anything like this before, so i was wondering on some advice. i couldnt find any comprehensible things online, considering im a noob, so if you could do…
PulsePanda
  • 1,806
  • 10
  • 33
  • 56
0
votes
2 answers

Java MIDI Parser?

Does anybody know a Java MIDI parser that will parse a MIDI into a tree like data structure where the nodes will be items such as the MTrks? I am doing some work on analyzing written music music and I want a format that contains hundreds of sample…
Mikhail
  • 7,749
  • 11
  • 62
  • 136
0
votes
0 answers

MIDIs sound different in Windows versus in a Java program

I'm playing MIDIs just fine, but they appear to be using different instruments when I play them in Java compared to when I play them with WMP 12 on Windows 7. Win7 plays them as they should be, the sounds are very 8-bit and organic as they are…
taylorthurlow
  • 2,953
  • 3
  • 28
  • 42
0
votes
1 answer

Pointer being freed was not allocated while capturing audio on a Mac?

I'm trying to record audio from my microphone on my Mac using Java. I found the code at the very bottom after a bit of searching on Google, but 1 out of every 3 or 4 times when I run it in Eclipse, the error: java(4946,0x1095f9000) malloc: *** error…
0
votes
1 answer

Can we use the Clip library in java to play the song at a different frequency

I know we can use Clip to play a song using clip.start(). However, is there a function in Clip that allows us to play the song at a different frequency from the original song?
Programmer
  • 6,565
  • 25
  • 78
  • 125
-1
votes
1 answer

play sound in java

I have five wav files. I want to play them serially from a single Java program using sourceDataLine. But my program is not maintaining the proper sequence. Can anyone provide me code segment?
PS Nayak
  • 409
  • 8
  • 20
-1
votes
1 answer

Java Sound LineUnavailableException: Format not supported

I am new to Java and I was attempting to create a sort of audio clip player that I can play with. I have no clue why this is happening and I just though I post it on here so someone smarter can take a look try { File snareFile = new…
Yup
  • 1
-1
votes
1 answer

Getting java.io.IOException:mark/reset not supported after uploading a file to play, pause, resume, loop audio

This is the code I have as of now: import javax.swing.JFileChooser; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.filechooser.FileSystemView; import javax.swing.JButton; import javax.swing.JFrame; import…
-1
votes
1 answer

audio playing in constructor instead of play method

so I've been working on my game library and I just got working on the sound aspect of it. But the problems are that the Sound starts playing from the constructor instead of the play method and also the stop doesn't work for the constructor and only…
fesd20
  • 1
  • 2
-1
votes
2 answers

Fast Forward implementation in Realtime Audio byte array in java

I am managing audio capturing and playing using java sound API (targetDataLine and sourceDataLine). Now suppose in a conference environment, one participant's audio queue size got greater than jitter size (due to processing or network) and I want to…
Nafiul Alam Fuji
  • 407
  • 7
  • 17
-1
votes
1 answer

Send/Receive Audio with a socket Java

I recently finished a simple socket-based messaging program that uses 256-byte block encryption and wanted to upgrade it to handle sound. After a bit of research, I found that javax.sound.* doesn't seem to be able to play or record a continuous…
user14831455
-1
votes
1 answer

Get max number of Clips that the Mixer can support?

I'm opening multiple audio files as instances of Clip by calling the following method for each audio file: final Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo(); final AudioInputStream audioInputStream =…
Cethy
  • 551
  • 6
  • 18
-1
votes
1 answer

Having a Problem playing .WAV files in java

I was creating what I deemed to be a quite simple program that played a .wav file in Java, but the sound is not playing when the program is started. All of my imports seem to be good, and I am not too sure why it is not playing, and I am starting to…
-1
votes
1 answer

How to play multiple WAV files when different buttons are clicked?

I am creating a simple tone dialer in Java. I am done putting up the buttons and their functionalities as in displaying it in the text field and all that. I just don't know how to get my buttons to make tones when clicked. I also need them to play…