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

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

Related

Could not play a clip sound

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

Adding sound to game. Help needed

So I have this code, and I would like to know how could I join it with the rest of my game, 'cause the only way it plays sound now is by selecting this class as a launcher. Also, could I get some info, what exactly is changed and why. I feel like I should get a better understanding of this code, since I just found the code, and pasted it :D
Code:
package main;
import main.Handler;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class AudioPlayer implements LineListener {
boolean playCompleted;
void play(String audioFilePath) {
File audioFile = new File(audioFilePath);
try {
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
AudioFormat format = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip audioClip = (Clip) AudioSystem.getLine(info);
audioClip.addLineListener(this);
audioClip.open(audioStream);
audioClip.start();
while (!playCompleted) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
audioClip.close();
} catch (UnsupportedAudioFileException ex) {
System.out.println("The specified audio file is not supported.");
ex.printStackTrace();
} catch (LineUnavailableException ex) {
System.out.println("Audio line for playing back is unavailable.");
ex.printStackTrace();
} catch (IOException ex) {
System.out.println("Error playing the audio file.");
ex.printStackTrace();
}
}
public void update(LineEvent event) {
LineEvent.Type type = event.getType();
if (type == LineEvent.Type.START) {
System.out.println("Playback started.");
} else if (type == LineEvent.Type.STOP) {
playCompleted = true;
System.out.println("Playback completed.");
}
}
public static void main(String[] args) {
String audioFilePath = "res/music/dark_theme.wav";
AudioPlayer player = new AudioPlayer();
player.play(audioFilePath);
}
}'
This class is a fairly normal class to use: Construct an instance, call some methods, and it does what it is expected to do. When you are using it as a launcher, all you're doing is calling the main method, which serves as an example of how to use this class:
public static void main(String[] args) {
String audioFilePath = "res/music/dark_theme.wav";
AudioPlayer player = new AudioPlayer();
player.play(audioFilePath);
}
Just construct an instance, and call play() on it with the name of the audio file intended.
However, be warned that this class isn't really a good example of how to go about doing this, for a few reasons:
It blocks while playing, meaning that you can't start playing sound and go about doing something different at the same time.
It can't play a sound more than once without incurring issues.
So, let's modify this class to not have these issues. This class will let you load a clip into memory, and start it asynchronously (meaning that you start it and then your program keeps running). The start() method starts it to play once, and the loop() method loops it forever. stop() is self-explanatory, and cleanup() should be called to release resources once you no longer need this audio clip. (Of course, if you intend to start playing the clip again soon, you should not cleanup() at that point).
import main.Handler;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class AudioPlayer{
Clip audioClip;
boolean playCompleted;
String path;
public AudioPlayer(String path){
this.path = path;
File audioFile = new File(path);
try {
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
AudioFormat format = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
audioClip = (Clip) AudioSystem.getLine(info);
audioClip.open(audioStream);
} catch (UnsupportedAudioFileException ex) {
System.out.println("The specified audio file is not supported.");
ex.printStackTrace();
} catch (LineUnavailableException ex) {
System.out.println("Audio line for playing back is unavailable.");
ex.printStackTrace();
} catch (IOException ex) {
System.out.println("Error playing the audio file.");
ex.printStackTrace();
}
}
void play() {
audioClip.start();
}
void loop(){
audioClip.loop(Clip.LOOP_CONTINUOUSLY);
}
void stop(){
audioClip.stop();
}
void cleanup(){
audioClip.close();
}
public static void main(String[] args) throws InterruptedException {
String audioFilePath = "res/music/dark_theme.wav";
AudioPlayer player = new AudioPlayer(audioFilePath);
player.play();
// give the sound time to play
while(true){
Thread.sleep(1000);
}
}
}

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