how to play an audio file in java

ht‮‬tps://www.lautturi.com
how to play an audio file in java

To play an audio file in Java, you can use the javax.sound.sampled package and the AudioInputStream and Clip classes.

Here is an example of how you can play an audio file in Java:

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import java.io.File;

public class AudioPlayer {
    public static void play(String fileName) {
        try {
            File file = new File(fileName);
            AudioInputStream stream = AudioSystem.getAudioInputStream(file);
            Clip clip = AudioSystem.getClip();
            clip.open(stream);
            clip.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

In this example, the AudioPlayer class has a play method that takes a file name as an argument and plays the audio file. The method starts by creating a File object with the file name and an AudioInputStream object with the file. Then, it creates a Clip object and opens the stream with it. Finally, it starts playing the audio file using the start method of the Clip object.

The javax.sound.sampled package supports a wide range of audio file formats, including WAV, AIFF, AU, and MP3. You can use the AudioSystem.getAudioInputStream method to read audio files in these formats and the Clip class to play them.

Keep in mind that this is just one way to play an audio file in Java. You can use different techniques and libraries to achieve the same result, such as using the javazoom library to play MP3 files or the javax.media package to play video files.

Created Time:2017-11-01 20:42:58  Author:lautturi