How to play sound in a java program?

4

I need to do a Java program, where the user enters the password and it is displayed on a TV monitor, this program will be used in a restaurant, so when the request is completed, the TV request and sound.

How do I add alert sound to the program?

    
asked by anonymous 15.04.2015 / 15:57

1 answer

8

This is an example where the program plays a sound in .wav format (the source is this answer in SOEN ):

import java.net.URL;
import javax.swing.*;
import javax.sound.sampled.*;

public class Teste {

    public static void main(String[] args) throws Exception {

        // Carrega o arquivo de áudio (não funciona com .mp3, só .wav) 
        URL oUrl = new URL("http://www.soundjay.com/button/beep-02.wav");
        Clip oClip = AudioSystem.getClip();
        AudioInputStream oStream = AudioSystem.getAudioInputStream(oUrl);
        oClip.open(oStream);

        oClip.loop(0); // Toca uma vez
        //clip.loop(Clip.LOOP_CONTINUOUSLY); // Toca continuamente (para o caso de músicas)

        // Para a execução (senão o programa termina antes de você ouvir o som)
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JOptionPane.showMessageDialog(null, "Clique pra fechar!");
            }
        });
    }
}

This native Java audio system ( AudioSystem ) does not support other formats, such as .mp3. If you have a .mp3 and you can not / want to convert it, you can try using this other option with JavaFX . p>     

15.04.2015 / 16:31