Playing sound in Java - SoundPlayer class

PHOTO EMBED

Thu Jun 30 2022 12:49:31 GMT+0000 (Coordinated Universal Time)

Saved by @Mahmouxd #java #sound

import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.File;
import java.io.IOException;

public class SoundPlayer {

    private static SoundPlayer instance;

    private Clip mClip;

    public static SoundPlayer get() {
        if (instance == null) instance = new SoundPlayer();
        return instance;
    }

    private SoundPlayer() {
        final File soundFile = new File("./res/my_sound.wav");

        try {
            mClip = AudioSystem.getClip();
            mClip.open(AudioSystem.getAudioInputStream(soundFile));

        } catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) {
            throw new RuntimeException(e);
        }
    }

    public void playMySound() {
        if (mClip != null) {
            mClip.setMicrosecondPosition(0);     // Reset to the start of the file
            mClip.start();
        }
    }
}
content_copyCOPY