Hello,
I want to add a sound file in a desktop application when it starts.
Please help me out.
Regards,
Sushant Taneja
SSCCExample:
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import javax.sound.sampled.*;
import javax.swing.*;
public class AppWithStartupSound extends JFrame {
private static final long serialVersionUID = 3259975599263984046L;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
AppWithStartupSound app = new AppWithStartupSound();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.startApp();
}
});
}
public AppWithStartupSound() {
initGUI();
}
private void startApp() {
playStartupSound();
setVisible(true);
}
private void endApp() {
System.exit(0);
}
private void playStartupSound() {
// Don't block the GUI Event Dispatch Thread, but open and
// play sound in a separate thread.
Runnable soundPlayer = new Runnable() {
public void run() {
try {
URL startupSound;
startupSound = new URL(
"
http://www.wav-sounds.com/various/beep.wav");
// startupSound = new URL(
// "
http://www.wav-sounds.com/various/applause.wav");
AudioInputStream audioInputStream = AudioSystem
.getAudioInputStream(startupSound);
AudioFormat audioFormat = audioInputStream
.getFormat();
DataLine.Info dataLineInfo = new DataLine.Info(
Clip.class, audioFormat);
Clip clip = (Clip) AudioSystem
.getLine(dataLineInfo);
clip.open(audioInputStream);
clip.start();
} catch (Exception e) {
e.printStackTrace();
}
}
};
Thread soundPlayingThread = new Thread(soundPlayer);
soundPlayingThread.start();
}
private void initGUI() {
setSize(300, 200);
setTitle("My application with startup sound");
JPanel jContentPane = new JPanel();
jContentPane.setLayout(new BorderLayout());
JButton jBtnExit = new JButton();
jBtnExit.setText("Exit");
jBtnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
endApp();
}
});
JTextArea jTextArea = new JTextArea();
jTextArea.setText("This is the application.\n\n"
+ "Did you hear the sound at startup?");
JScrollPane jScrollPane = new JScrollPane();
jScrollPane.setViewportView(jTextArea);
jContentPane.add(jBtnExit, BorderLayout.SOUTH);
jContentPane.add(jScrollPane, BorderLayout.CENTER);
setContentPane(jContentPane);
}
} // end of class AppWithStartupSound