I have created a class to play the sound when I click the buttons.
Here is the code :
public void playSound()
{
try
{
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("beep-1.wav"));
Clip clip = AudioSystem.getClip( );
clip.open(audioInputStream);
clip.start( );
}
catch(Exception e)
{
System.out.println("Error with playing sound.");
}
}
When I want to implement it into the the ButtonListener method, it's seem like no sound is played.
Here the ButtonListener code :
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (replayButton == e.getSource())
{
playSound();
}
}
}
What's wrong with the code?
EDIT :
Basically I'm trying to create a simple memory game, and I want to add sound to the buttons when clicked.
SOLVED :
Seems like the audio file I downloaded from Soundjay got problem, and hence, the audio file can't be played. #_#
Use
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
playSound();
}
});
This should work:
public class Test extends JFrame {
public static void main(String[] args) {
new Test();
}
public Test() {
JButton button = new JButton("play");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
playSound();
}});
this.getContentPane().add(button);
this.setVisible(true);
}
public void playSound() {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("beep.wav"));
Clip clip = AudioSystem.getClip( );
clip.open(audioInputStream);
clip.start( );
}
catch(Exception e) {
e.printStackTrace( );
}
}
}
Note that during the play of your file, the GUI will be not responsable. Use the approach from Joop Eggen in your listener to correct this. It will play the file asynchronous.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
playSound();
}
});
Any stacktrace, please??? did you add listener to the button???
Anyway the standart way have some bugs when targeting cross-platform. Use Java Media Framework at http://www.oracle.com/technetwork/java/javase/tech/index-jsp-140239.html.
Related
I'm using java to try and make an alarm of sorts. I want to input a time and then when it hits zero, play a specific .mp3. The countdown works fine, but when it hits zero and tries to play the mp3, it can't find the file. Advice? I've already searched the site and can't find anything simple enough for me to use (I'm a beginner). Here's what I got so far:
public static void main(String[] args) {
int timer;
File song = new File("C:/Users/N/Documents/Random/Handies/Proj/Song.mp3");
timer = 1;
timer*=1;
while (timer != 0)
{
try
{
Thread.sleep(1000);
} catch (InterruptedException e) {}
timer -= 1;
System.out.println(timer);
}
if (timer == 0)
Play(song);
}
public static void Play(File song)
{
try
{
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(song));
clip.start();
}
catch (Exception exc)
{
exc.printStackTrace(System.out);
}
}
With JavaFX you can easily play the MP3 like this:
public class Test extends javafx.application.Application {
#Override
public void start(Stage primaryStage) throws Exception {
File file = new File("/path/test.mp3");
Media media = new Media(file.toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();
}
}
I usually find it hard using AudioSystem for this kind of thing.
I've been trying to play sound1 and sound2 using AudioClips. This is my code:
import javax.sound.sampled.*;
public class Sound {
private Clip clip;
public static final Sound sound1 = new Sound("src/Sounds/Classic_Horror_2.wav");
public static final Sound sound2 = new Sound("src/Sounds/Classic Horror 3.mp3");
public Sound (String fileName) {
try {
AudioInputStream ais = AudioSystem.getAudioInputStream(Sound.class.getResource(fileName));
clip = AudioSystem.getClip();
clip.open(ais);
} catch (Exception e) {
e.printStackTrace();
}
}
public void play() {
try {
if (clip != null) {
new Thread() {
public void run() {
synchronized (clip) {
clip.stop();
clip.setFramePosition(0);
clip.start();
}
}
}.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void stop(){
if(clip == null) return;
clip.stop();
}
public void loop() {
try {
if (clip != null) {
new Thread() {
public void run() {
synchronized (clip) {
clip.stop();
clip.setFramePosition(0);
clip.loop(Clip.LOOP_CONTINUOUSLY);
}
}
}.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean isActive(){
return clip.isActive();
}
}
When I try to do Sound.sound1.loop(); or Sound.sound1.play(); I get a null pointer exception. Same goes for sound2. Here are the exact errors messages:
java.lang.NullPointerException
at com.sun.media.sound.StandardMidiFileReader.getSequence(StandardMidiFileReader.java:207)
at javax.sound.midi.MidiSystem.getSequence(MidiSystem.java:841)
at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(SoftMidiAudioFileReader.java:178)
at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1147)
at Sound.<init>(Sound.java:12)
at Sound.<clinit>(Sound.java:7)
at IntroductionComponent.<init>(IntroductionComponent.java:54)
at IntroductionGUI.main(IntroductionGUI.java:9)
java.lang.NullPointerException
at com.sun.media.sound.StandardMidiFileReader.getSequence(StandardMidiFileReader.java:207)
at javax.sound.midi.MidiSystem.getSequence(MidiSystem.java:841)
at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(SoftMidiAudioFileReader.java:178)
at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1147)
at Sound.<init>(Sound.java:12)
at Sound.<clinit>(Sound.java:8)
at IntroductionComponent.<init>(IntroductionComponent.java:54)
at IntroductionGUI.main(IntroductionGUI.java:9)
I have repeatedly browsed stackoverflow to look for possible fixes, however it may be that fileName returns null constantly, or that my URL's are somehow incorrect. That said, for all I know it could be anything. Any suggestions on how to fix this?
The inclusion of src in your paths...
public static final Sound sound1 = new Sound("src/Sounds/Classic_Horror_2.wav");
public static final Sound sound2 = new Sound("src/Sounds/Classic Horror 3.mp3");
is your key problem, src won't exist once the application is build and package, you should never refer to src ever.
You should probably be using something more like...
public static final Sound sound1 = new Sound("/Sounds/Classic_Horror_2.wav");
public static final Sound sound2 = new Sound("/Sounds/Classic Horror 3.mp3");
public Sound (String fileName) {
try {
AudioInputStream ais = AudioSystem.getAudioInputStream(getClass().getResource(fileName));
clip = AudioSystem.getClip();
clip.open(ais);
} catch (Exception e) {
e.printStackTrace();
}
}
Personally, I'd make Sound require a URL...
public Sound (URL url) {
try {
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
clip = AudioSystem.getClip();
clip.open(ais);
} catch (Exception e) {
e.printStackTrace();
}
}
This way there's no confusion over what String means and you can pass a reference from embedded resources, file references or even from the net
Also from memory, clip.start() creates it's own thread, so there's no need to create your own
I've searched and read another topics but i still can't solve my problems. I had one java main class and one java jframe. I wanna add jslider to change volume in my mp3 player. What should i do?
my_player2_func
class my_player2_func{
static Player player;
static void play() {
try {
FileInputStream fe = new FileInputStream(my_player2_main.str);
player = new Player(fe);
} catch (Exception ex) {
System.out.println(ex);
}
new Thread(new Runnable() {
#Override
public void run() {
try {
player.play();
} catch (Exception ex) {
System.out.println(ex);
}
}
}).start();
}
static void stop() {
if (player != null)
player.close();
} }
my_player2_main
public my_player2_main() {
initComponents();
}
static String str;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
my_player2_func.play();
}
private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {//what should i do here?}
JLayer is a decoder. By its very definition it does not know anything about volume, thats the job of the audio hardware that plays the sound.
Your problem stems from the fact that you are using the Player and defaul JavaSoundAudioDevice classes, which were meant as short, simple examples how to play an MP3, not as building blocks for a full fledged audio player.
You will have to copy or modify the source of JavaSoundAudioDevice (part of JLayer source) and hack it to support volume control. Et voila you can control volume.
I want to create 2 JMenuItem that can start and stop the background audio.
Here is my code :
public class MainClass extends JFrame
{
private AudioInputStream audioInputStream;
private Clip clip;
public MainClass(String title)
{
try
{
audioInputStream = AudioSystem.getAudioInputStream(new File("Background.wav"));
clip = AudioSystem.getClip();
clip.loop(Clip.LOOP_CONTINUOUSLY);
clip.open(audioInputStream);
}
catch(Exception e)
{
System.out.println("Error with playing sound.");
e.printStackTrace();
}
}
public void startSound()
{
clip3.start();
settingSubMenuItem1.setEnabled(false);
settingSubMenuItem2.setEnabled(true);
}
public void stopSound()
{
clip3.stop();
settingSubMenuItem1.setEnabled(true);
settingSubMenuItem2.setEnabled(false);
}
private class MenuItemListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == settingSubMenuItem1)
{
startSound();
}
if(e.getSource() == settingSubMenuItem2)
{
stopSound();
}
}
}
}
When I click the settingSubMenuItem1, it's work fine, audio is played.
But when I click the settingSubMenuItem2, there is errors and if click again settingSubMenuItem1, there will no more sound.
Here is the errors :
Error with playing sound.
java.lang.IllegalStateException: Clip is already open with format PCM_SIGNED 44100.0 Hz, 16 bit, stereo, 4 bytes/frame, little-endian and frame lengh of 7658
What is the error of my program?
This SSCCE is a 'null result' here, in that the audio restarts (tried at least 3 times) with no exceptions.
import java.net.URL;
import java.awt.event.*;
import javax.swing.*;
import javax.sound.sampled.*;
public class RestartableLoopSound {
public static void main(String[] args) throws Exception {
URL url = new URL(
"http://pscode.org/media/leftright.wav");
final Clip clip = AudioSystem.getClip();
AudioInputStream ais = AudioSystem.
getAudioInputStream( url );
clip.open(ais);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final JToggleButton b = new JToggleButton("Loop");
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (b.isSelected()) {
// loop continuously
clip.loop(Clip.LOOP_CONTINUOUSLY);
} else {
clip.stop();
}
}
};
b.addActionListener(listener);
JOptionPane.showMessageDialog(null, b);
}
});
}
}
I'm trying to use the code which available on: How can I play sound in Java?
but I can't post question there since this is a new account and only have 1 reputation.
original code:
public static synchronized void playSound(final String url) {
new Thread(new Runnable() { // the wrapper thread is unnecessary, unless it blocks on the Clip finishing, see comments
public void run() {
try {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(Main.class.getResourceAsStream("/path/to/sounds/" + url));
clip.open(inputStream);
clip.start();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}).start();
}
and this is my code:
package sound_test;
import javax.sound.sampled.*;
public class Main {
public static synchronized void playSound(final String url) {
new Thread(new Runnable() {
public void run() {
try {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(Main.class.getResourceAsStream("/path/to/sounds/" + url));
clip.open(inputStream);
clip.start();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}).start();
}
public static void main(String[] args) {
// TODO code application logic here
playSound("C:\\warning_test.wav");
}
}
When I run the code i receive "null" as the output and no sound came out.
I've checked the file name and the path, it's correct.
screenshots:
http://puu.sh/pkYo
http://puu.sh/pkZl
Thank you in advance.
you could do
AudioInputStream inputStream=AudioSystem.getAudioInputStream(new File(url));
also add a delay after click.start(); i.e Thread.Sleep(4000);
or if you want to make sure it plays the entire audio sample you could use a simple snippet such as
import javax.sound.sampled.*;
import java.io.File;
public class Main implements LineListener {
private boolean done = false;
public void update(LineEvent event) {
if(event.getType() == LineEvent.Type.STOP || event.getType() == LineEvent.Type.CLOSE) {
done = true;
}
}
public void waitonfinish() throws InterruptedException {
while(!done) {
Thread.sleep(1000);
}
}
public static void playSound(final String url) {
try {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File(url));
Main control = new Main();
clip.addLineListener(control);
clip.open(inputStream);
clip.start();
control.waitonfinish();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
public static void main(String[] args) {
// TODO code application logic here
playSound("C:\\warning_test.wav");
}
}
`
You copied the code entirely without noticing the in the original, it points to
path/to/sounds
since you give it the full path, u should replace it with just url:
AudioInputStream inputStream = AudioSystem.getAudioInputStream(Main.class.getResourceAsStream(url));
EDIT:
I tried here and got null as well.
I changed it to create the audioInput from a file:
import java.io.File;
import javax.sound.sampled.*;
public class Main {
public static synchronized void playSound(final File file) {
new Thread(new Runnable() {
public void run() {
try {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(file);
clip.open(inputStream);
clip.start();
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getMessage());
}
}
}).start();
}
public static void main(String[] args) {
// TODO code application logic here
File file = new File("C:\\warning_test.wav");
playSound(file);
}