IOException markreset not supported with Java Sound on export - java

Ok so i made a game in java and i exported it. In Eclipse everything works perfectly but when i export the jar there are some problems. When you collide with another rectangle it should play a sound (In eclipse it works but not exported).
Here is my class for sounds:
package sound;
import java.io.InputStream;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class GameSounds
{
static String hitPath = "/resources/8bit_bomb_explosion.wav";
public static synchronized void hit()
{
try
{
InputStream audioInStream = GameSounds.class.getResourceAsStream(hitPath);
AudioInputStream inputStream = AudioSystem.getAudioInputStream(audioInStream);
Clip clip = AudioSystem.getClip();
clip.open(inputStream);
clip.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
and i used java -jar ProjectZero.jar to open up the console while playing and here is the error i get when it should play a sound:
java.io.IOException markreset not supported
at java.util.zip.InflaterInputStream.reset(Unknown Source)
at java.io.FilterInputStream.reset(Unknown Source)
at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(Unkno
wn Source)
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at sound.GameSounds.hit(GameSounds.java14)
at main.Main.doLogic(Main.java136)
at main.Main.run(Main.java100)
at java.lang.Thread.run(Unknown Source)
I tried exporting the resources into the jar but no success.
I tried putting the resources folder in the same folder with the jar but it doesn't work either.

Java Sound requires a repositionable input stream. Either use getResource(String) for an URL (out of which JS will create such a stream), or wrap the original stream to make it so.
E.G. copied from the Java Sound info. page.
import java.net.URL;
import javax.swing.*;
import javax.sound.sampled.*;
public class LoopSound {
public static void main(String[] args) throws Exception {
URL url = new URL(
"http://pscode.org/media/leftright.wav");
Clip clip = AudioSystem.getClip();
// getAudioInputStream() also accepts a File or InputStream
AudioInputStream ais = AudioSystem.
getAudioInputStream( url );
clip.open(ais);
clip.loop(Clip.LOOP_CONTINUOUSLY);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// A GUI element to prevent the Clip's daemon Thread
// from terminating at the end of the main()
JOptionPane.showMessageDialog(null, "Close to exit!");
}
});
}
}
See also the embedded-resource info. page.

Related

Why does attempting to get a Clip throw exception?

I have been following this tutorial for Java 1.7 and I am sure I have the code right. However, Java throws an IllegalArgumentException at runtime.
I've tried to catch it in an existing catch block, using Java's slightly-newer multi-catch. However, it simply throws exceptions.
Here is the beginning of my code.
Mixer.Info[] mixInfos = AudioSystem.getMixerInfo();
/*
for (Mixer.Info info : mixInfos)
{
System.out.println(info.getName() + " - " + info.getDescription());
}
*/
mixer = AudioSystem.getMixer(mixInfos[0]);
DataLine.Info dataInfo = new DataLine.Info(Clip.class, null);
try
{
clip = (Clip) mixer.getLine(dataInfo);
}
I expect that the code will continue running and play the Clip but I get this exception:
Exception in thread "main" java.lang.IllegalArgumentException: Line unsupported: interface Clip
at java.desktop/com.sun.media.sound.PortMixer.getLine(PortMixer.java:131)
at main.Driver.main(Driver.java:35)
Note: If this isn't forward compatible, please explain.
I think you should check your imports. AFAIK, the libraries for sound are all in javax.sound.sampled. The PortMixer is in com.sun.media.sound.
The author of the tutorial is going to a lot more trouble than is necessary. Instead of hardcoding a specific Mixer, you can just let the system pick defaults. This is probably the best strategy, as PC's out in the world are going to have diverse hardware configurations.
Following is an example that might be helpful. Notice that we don't even bother to declare a Mixer.
import java.io.IOException;
import java.net.URL;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class BasicClipExample {
public static void main(String[] args) {
BasicClipExample bc = new BasicClipExample();
try {
bc.run();
} catch (UnsupportedAudioFileException | IOException
| LineUnavailableException | InterruptedException e) {
e.printStackTrace();
}
}
private void run() throws UnsupportedAudioFileException,
IOException, LineUnavailableException, InterruptedException
{
String filename = "a3.wav";
URL url = this.getClass().getResource("audio/" + filename);
System.out.println(url);
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
DataLine.Info info = new DataLine.Info(Clip.class, ais.getFormat());
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(ais);
clip.start();
Thread.sleep(6000);
clip.close();
}
}
This example assumes that your audio file is in a subdirectory called "/audio".
It also has a sleep command to keep the program running while the Clip is playing. Clips run under their own thread, but the thread is a "daemon" type and will not prevent a Java program from closing. My a3.wav is a recording of a bell that happens to last about 5 seconds.
Last thing, the above code does not use a Clip in the ideal fashion. The concept of a Clip is that it is for re-use. Reloading the clip variable before playing it each time it is played is inefficient. The clip variable should be loaded only once, and then played on demand. If you have clip.open() and clip.start() as contiguous lines of code, you should probably either be using a SourceDataLine instead of a Clip, or you should recode and put the two commands into separate methods.

How to play .wav files in Java (looped)?

I've been rampaging about for a couple of hours now looking for sample code that can play simple wav files in Java. However, none of the ones I've received are working for me. Maybe it's just me that doesn't understand how to operate the sample code but could anyone provide me with sample code and "instructions" on how to get it working correctly. Any help would be much appreciated.
This code will create a clip and play it continuously once started:
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new URL(filename)));
clip.start();
clip.loop(Clip.LOOP_CONTINUOUSLY);
There are more modern ways to do this, but the applet class AudioClip might satisfy your needs:
import java.applet.Applet;
import java.applet.AudioClip;
final AudioClip clip = Applet.newAudioClip(resourceUrl);
To play it once:
clip.play();
To loop:
clip.loop();
clip.stop();
See Javadocs for Applet and AudioClip
getAudioClip
public AudioClip getAudioClip(URL url)
Returns the AudioClip object specified by the URL argument.
This method always returns immediately, whether or not the audio clip exists. When this applet attempts to play the audio clip, the data will be loaded.
Parameters:
url - an absolute URL giving the location of the audio clip.
Returns:
the audio clip at the specified URL.
You don't need to actually be doing anything with applets for this to work. It will work fine in a regular Java application.
import java.io.File;
import javax.sound.sampled.*;
public void play(File file)
{
try
{
final Clip clip = (Clip)AudioSystem.getLine(new Line.Info(Clip.class));
clip.addLineListener(new LineListener()
{
#Override
public void update(LineEvent event)
{
if (event.getType() == LineEvent.Type.STOP)
clip.close();
}
});
clip.open(AudioSystem.getAudioInputStream(file));
clip.start();
}
catch (Exception exc)
{
exc.printStackTrace(System.out);
}
}

MalformedURLException no protocol. How to fix?

So I have this Code:
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;
public class SoundTest {
public static void main(String[] args) throws Exception {
URL url = new URL("Sprites/Omni's Tones/New tones/bubblespawn_01.wav");
AudioClip clip = Applet.newAudioClip(url);
AudioClip clip2 = Applet.newAudioClip(url);
clip.play();
Thread.sleep(1000);
clip2.loop();
Thread.sleep(20000);
clip2.stop();
System.out.println("end");
}
}
An error Appears:
Exception in thread "main" java.net.MalformedURLException: no protocol: Sprites/Omni's Tones/New tones/bubblespawn_01.wav
at java.net.URL.<init>(URL.java:586)
at java.net.URL.<init>(URL.java:483)
at java.net.URL.<init>(URL.java:432)
at com.edu4java.minitennis7.SoundTest.main(SoundTest.java:10)
How do I fix this? Thank you!
It seems that I need to add more lines to my code,
If you are running it inside the Applet then try with Applet#getCodeBase() and Applet#getDocumentBase
URL url = getDocumentBase();
AudioClip audioClip = getAudioClip(url, "music/abc.wav")
If it's running in a standalone application then choose one based on music file location:
// Read from same package
InputStream inputStream = getClass().getResourceAsStream("abc.wav");
// Read from music folder parallel to src in your project
File file = new File("music/abc.wav");
// Read from src/music folder
URL url = getClass().getResource("/music/abc.wav");
// Read from src/music folder
InputStream inputStream = getClass().getResourceAsStream("/music/abc.wav");

Error getting audio input stream from input URL

I am trying to play a .WAV in Java using the code from the javasound.info:
import java.net.URL;
import javax.swing.*;
import javax.sound.sampled.*;
public class LoopSound {
public static void main(String[] args) throws Exception {
URL url = new URL(
http://www.mediafire.com/listen/vgtpaigmj3un9ii/Untitled34.wav");
Clip clip = AudioSystem.getClip();
// getAudioInputStream() also accepts a File or InputStream
AudioInputStream ais = AudioSystem.
getAudioInputStream( url );
clip.open(ais);
clip.loop(Clip.LOOP_CONTINUOUSLY);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// A GUI element to prevent the Clip's daemon Thread
// from terminating at the end of the main()
JOptionPane.showMessageDialog(null, "Close to exit!");
}
});
}
}
But I am getting the following error:
Exception in thread "main" javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input URL
at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1153)
at LoopSound.main(Wanderando.java:13)
I assume that the problem is with the URL itself and not the code, but I cannot for the life of me come across a service to upload and stream a .WAV file so that the program can capture the audio like in the original code with the :
http://pscode.org/media/leftright.wav
I am not sure if the code would have to be tweaked a bit for the to support mediafire's player or if there is another service for upload that support this.
Any help would be very appreciated.

How to play an mp3 file in java

I am trying to play a song (mp3 file) in java. I have been looking around for a few hours now and none of the ways I found worked properly.
public void play()
{
String song = "song.mp3";
Media track = new Media(song);
MediaPlayer mediaPlayer = new MediaPlayer(track);
mediaPlayer.play();
}
I have tried doing that but it gives me errors.
I have imported JMF and JLayer.
I have also read other questions that are like this one on this forum and none of them have helped me.
I just need a hand to help play an mp3 file.
The easiest way I found was to download the JLayer jar file from http://www.javazoom.net/javalayer/sources.html and to add it to the Jar library http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29
Here is the code for the class
public class SimplePlayer {
public SimplePlayer(){
try{
FileInputStream fis = new FileInputStream("File location.");
Player playMP3 = new Player(fis);
playMP3.play();
}catch(Exception e){System.out.println(e);}
}
}
and here are the imports
import javazoom.jl.player.*;
import java.io.FileInputStream;
For this you'll need to install Java Media Framework (JMF) in your PC. One you have it installed,then try this piece of code:
import javax.media.*;
import java.net.*;
import java.io.*;
import java.util.*;
class AudioPlay
{
public static void main(String args[]) throws Exception
{
// Take the path of the audio file from command line
File f=new File("song.mp3");
// Create a Player object that realizes the audio
final Player p=Manager.createRealizedPlayer(f.toURI().toURL());
// Start the music
p.start();
// Create a Scanner object for taking input from cmd
Scanner s=new Scanner(System.in);
// Read a line and store it in st
String st=s.nextLine();
// If user types 's', stop the audio
if(st.equals("s"))
{
p.stop();
}
}
}
You may run into unable to handle formaterror, that is because Java took out the MP3 support by default (pirate copyright issue), you are required to install a “JMF MP3 plugin” in order to play MP3 file.
Go Java’s JMF website to download it
http://java.sun.com/javase/technologies/desktop/media/jmf/mp3/download.html
To be sure that you are using a supported format file, check here:
http://www.oracle.com/technetwork/java/javase/formats-138492.html
If you are using windows7, you may have to read this as well:
https://forums.oracle.com/forums/thread.jspa?threadID=2132405&tstart=45
How about JavaFX application-
import java.net.URL;
import javafx.application.Application;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
public class VLC extends Application {
void playMedia() {
String mp3 = "00- Tu Hi Mera.mp3";
URL resource = getClass().getResource(mp3);
System.out.println(resource.toString());
Media media = new Media(resource.toString());
MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();
}
public static void main(String args[]) {
new VLC().playMedia();
}
#Override
public void start(Stage stage) throws Exception {
}
}

Categories