Sound.

How do you add sound to an application in Netbeans 5.5?It isn't an applet. I want to add sound when I press a button.
[139 byte] By [vluvlua] at [2007-11-27 8:36:12]
# 1
You can use the static method Applet.newAudioClip(URL).After that, you may want to look into starting a SwingWorker task to play the sound after an ActionEvent is triggered by clicking a button.
RATiXa at 2007-7-12 20:33:03 > top of Java-index,Java Essentials,Java Programming...
# 2
Does it work with an application?Because it isn't an applet.
vluvlua at 2007-7-12 20:33:03 > top of Java-index,Java Essentials,Java Programming...
# 3
Yes, it will work with any application running in a proper JRE.
RATiXa at 2007-7-12 20:33:03 > top of Java-index,Java Essentials,Java Programming...
# 4
Could you write an example?
vluvlua at 2007-7-12 20:33:03 > top of Java-index,Java Essentials,Java Programming...
# 5

JButton button = new JButton("click to play sound");

final URL audioUrl = getClass().getClassLoader().getResource("audio.wav");

button.addActionListener(new ActionListener() {

public void ActionPerformed(ActionEvent evt) {

new SwingWorker() {

protected Object doInBackground() {

Applet.newAudioClip(audioUrl).play();

}

}.execute();

}

});

There are plenty of tutorials by Sun as well as the API docs if you need more help.

RATiXa at 2007-7-12 20:33:03 > top of Java-index,Java Essentials,Java Programming...
# 6

> Could you write an example?

/*--

// Author List:

//deAppel<Creator>

//

// Description:

//Play audio file using sun.audio package

//

// Environment:

//This software was developed using Eclipse and Java 1.6

//

// Copyright Information:

//Copyright (C) 2007<Institution><None>

//Ark de Appel www.engineeringserver.com

//

//-*/

import java.awt.Container;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.FileInputStream;

import java.io.IOException;

import javax.swing.JButton;

import javax.swing.JFrame;

import sun.audio.AudioPlayer;

import sun.audio.AudioStream;

public class PlayAudio extends JFrame implements ActionListener{

JButton button;

boolean stop = true;

public PlayAudio(){

Container c = getContentPane();

button = new JButton("Play");

button.addActionListener(this);

c.add(button);

setTitle("Play audio");

setSize(200,100);

setVisible(true);

}

public void actionPerformed(ActionEvent e){

try{

AudioPlayer p=AudioPlayer.player;

AudioStream as =

new AudioStream(new FileInputStream("your file here"));

p.start(as);

}

catch(IOException IOE){}

}

public static void main(String[] args){

PlayAudio PA = new PlayAudio();

}

}

deAppela at 2007-7-12 20:33:03 > top of Java-index,Java Essentials,Java Programming...