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);
}
});
}
}
Related
I'm new to programming and I couldnt figure out how to play a sound clip. The code run smoothly but there is no sound coming out from intellij.
Here's my code
package ProjectWumpus;
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
public class testClass {
public static void main(String[] args) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
File file = new File("C:\\Users\\Correct_Answer_Sound_Effect.wav");
AudioInputStream audiostream = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(audiostream);
clip.start();
My audio from my pc is working fine.
In the comments, both respondents pointed out that the program closes before the Clip has a chance to play. Clips immediately return control back to the main thread. The code which executes the playback is on a daemon thread. Daemon threads will not hold open a program that is ready to close.
FWIW, Here is perhaps a better way to test. In the following code a simple GUI: a button that plays the sound. This is a more typical of how clips are used.
public class TestClip {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
public void run()
{
DemoFrame frame = new DemoFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class DemoFrame extends JFrame {
private static final long serialVersionUID = 1L;
private Clip clip;
public DemoFrame() {
setSize(300, 100);
JPanel panel = new JPanel();
JButton button = new JButton("Play clip");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clip.setFramePosition(0);
clip.start();
}
});
panel.add(button);
add(panel);
// Set up the Clip
URL url = this.getClass().getResource("mySound.wav");
try {
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
clip = AudioSystem.getClip();
clip.open(ais);
} catch ( LineUnavailableException e) {
e.printStackTrace();
} catch (UnsupportedAudioFileException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
I recommend using URL over File for the getAudioInputStream method. In this case, it's assumed the audio resource is in the same directory as the class that is calling it. A URL has the benefit of working when the class is packaged in a jar (unlike File).
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
this is the first time for me that I try to use a song within my code.
I have been following a webpage which explains how to play songs (http://www3.ntu.edu.sg/home/ehchua/programming/java/J8c_PlayingSound.html), but I run into the error ava.lang.IllegalArgumentException: Invalid format.
I don't understand why this happens and what I could do to play a song.
This is the code that doesn't work:
private void startMusic() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
// from a wave File
File soundFile = new File("/home/simone/OhHa/Pakman02/src/main/java/Pakman/ArsenioLupin.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
// For small-size file only. Do not use this to open a large file over slow network, as it blocks.
// start()
clip.start(); // play once
// Loop()
// clip.loop(0); // repeat none (play once), can be used in place of start().
// clip.loop(5); // repeat 5 times (play 6 times)
clip.loop(Clip.LOOP_CONTINUOUSLY); // repeat forever
}
Any suggestions?
try this. note the import of the javax.sound.sampled.*
import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;
import javax.swing.*;
public class SoundClipTest extends JFrame {
// Constructor
public SoundClipTest() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Test Sound Clip");
this.setSize(300, 200);
this.setVisible(true);
try {
// Open an audio input stream.
URL url = this.getClass().getClassLoader().getResource("/home/simone/OhHa/Pakman02/src/main/java/Pakman/ArsenioLupin.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
// Get a sound clip resource.
Clip clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
clip.open(audioIn);
clip.start();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new SoundClipTest();
}
}
an alternative is
import javax.swing.*;
import sun.audio.*;
import java.awt.event.*;
import java.io.*;
public class Sound {
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(200,200);
JButton button = new JButton("Click me");
frame.add(button);
button.addActionListener(new AL());
frame.show(true);
}
public static class AL implements ActionListener{
public final void actionPerformed(ActionEvent e){
music();
}
}
public static void music(){
AudioPlayer MGP = AudioPlayer.player;
AudioStream BGM;
AudioData MD;
ContinuousAudioDataStream loop = null;
try{
BGM = new AudioStream(new FileInputStream("C:\home\simone\OhHa\Pakman02\src\main\java\Pakman\ArsenioLupin.wav"));
MD = BGM.getData();
loop = new ContinuousAudioDataStream(MD);
}catch(IOException error){
System.out.print("file not found");
}
MGP.start(loop);
}
}
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.
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);
}