Could not play a clip sound - java

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).

Related

Is there a way to stop an audio clip playing in the middle of the clip?

I am developing an alarm clock program that plays an audio clip as an alarm. I can successfully play an audio clip, and terminate an inactive alarm. However, when I try to terminate an alarm that is currently playing, the audio keeps playing. Solutions I've tried were setting the clip to null, clip.stop(); and
public void stopSound(Clip clip){
clip.stop();
clip.flush();
clip.close();
}
Is there a way to end a clip at any percentage through a clip?
This works for me. It stops after 5 seconds of playing.
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
playMusic("<Type your path to music here>");
}
static void playMusic(String musicLocation) {
new Thread(() -> {
try {
File musicPath = new File(musicLocation);
if (musicPath.exists()) {
AudioInputStream audioInput = AudioSystem.getAudioInputStream(musicPath);
Clip clip = AudioSystem.getClip();
clip.open(audioInput);
clip.start();
TimeUnit.SECONDS.sleep(5);
clip.stop();
} else {
System.out.println("Can't find file");
}
} catch (IOException | UnsupportedAudioFileException | LineUnavailableException | InterruptedException e) {
throw new RuntimeException(e);
}
}).start();
}
}

Trying to play music in Java: java.lang.IllegalArgumentException: Invalid format

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);
}
}

Error playing AudioInputStream

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);
}
});
}
}

What is wrong with my code so it can't play wav file?

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);
}

Stop method not working

can anybody tell me why the following code doesn't work properly?
I want to play and stop an audio file.
I can do the playback but whenever I click the stop button nothing happens.
Here's the code :
Thank you.
..................
import java.io.*;
import javax.sound.sampled.*;
import javax.swing.*;
import java.awt.event.*;
public class SoundClipTest extends JFrame {
final JButton button1 = new JButton("Play");
final JButton button2 = new JButton("Stop");
int stopPlayback = 0;
// Constructor
public SoundClipTest() {
button1.setEnabled(true);
button2.setEnabled(false);
// button play
button1.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
button1.setEnabled(false);
button2.setEnabled(true);
play();
}// end actionPerformed
}// end ActionListener
);// end addActionListener()
// button stop
button2.addActionListener(
new ActionListener() {
public void actionPerformed(
ActionEvent e) {
//Terminate playback before EOF
stopPlayback = 1;
}//end actionPerformed
}//end ActionListener
);//end addActionListener()
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Test Sound Clip");
this.setSize(300, 200);
JToolBar bar = new JToolBar();
bar.add(button1);
bar.add(button2);
bar.setOrientation(JToolBar.VERTICAL);
add("North", bar);
add("West", bar);
setVisible(true);
}
void play() {
try {
final File inputAudio = new File("first.wav");
// First, we get the format of the input file
final AudioFileFormat.Type fileType =
AudioSystem.getAudioFileFormat(inputAudio).getType();
// Then, we get a clip for playing the audio.
final Clip c = AudioSystem.getClip();
// We get a stream for playing the input file.
AudioInputStream ais = AudioSystem.getAudioInputStream(inputAudio);
// We use the clip to open (but not start) the input stream
c.open(ais);
// We get the format of the audio codec
// (not the file format we got above)
final AudioFormat audioFormat = ais.getFormat();
c.start();
if (stopPlayback == 1) {
c.stop();
}
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}// end play
public static void main(String[] args) {
//new SoundClipTest().play();
new SoundClipTest();
}
}
your if (stopPlayback == 1 ) will only be run once -- you'll have to enclose it in a while(true) loop to make sure it keeps being evaluated, make sure you add a pause as well otherwise you will burn a lot of unnecessary cycles.
Update: I was assuming you ran a second thread to watch on the stopPlayback value - I now see this is not the case. Why don't you just call the c.stop() from your ActionListener?

Categories