How to play audio automatically on startup of a program?

Asked

Viewed 288 times

1

I want the audio to play as soon as the software starts. If you have any suggestions for positioning the audio button in the main frame,...

Follow code for analysis:

Main class

package Interface;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        ClasseFrame cf= new ClasseFrame();
        cf.setVisible(true);

        //Chama o método para reproduzir o audio
            new TocarSom();
        }               
    }

Class to play audio

package Interface;

import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;

public class TocarSom extends JFrame {

    JButton tocar = new JButton(new ImageIcon("/Imagens/Blue_Bird.jpg"));

    public TocarSom() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        tocar.setBounds(480, 250, 250, 250);//(coluna,linha,comprimento,largura);
        setLocationRelativeTo(null);
        setVisible(true);

        add(tocar);
        tocar.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                play("BlueBird");
            }
        });
    }

    public void play(String nomeDoAudio) {
        URL url= TocarSom.class.getResource(nomeDoAudio+".wav");
        AudioClip audio= Applet.newAudioClip(url);
        audio.play();
    }
}
  • And what’s wrong with the code?

  • With no code, I just don’t know how to play it automatically

  • Already tried to put in the builder?

  • This "Tocarsom" class is just to play the sound or is it also a screen?

  • I tried to put it in the constructor and it worked. The "Tocarsom" class is screen tbm, has Jbutton q plays the audio by clicking;

  • Which class should play sound at the beginning after all?

  • The Main class .

Show 2 more comments

1 answer

2


Try it like this:

package Interface;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        ClasseFrame cf= new ClasseFrame();
        cf.setVisible(true);

        //Chama o método para reproduzir o audio
            new TocarSom().play("nome do arquivo de audio");
        }               
    }
  • IT WORKED!!! Thank you very much guy!!!

  • @Nakury if the answer helped solve the problem, you can accept it by clicking on v so that the question can be given as already solved.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.