I've been researching sound files in Java for the past couple of days and I thought I finally could try and get some sound running.
I coded a small segment but unfortunately, there is no sound be played after running it.
Is there a bug somewhere that I'm not seeing or does this code not work. Thanks.
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;
public class driver {
public static void main ( String [] args ) throws Exception {
URL resourceUrl = new URL("file:;///C:/Users/Jack/Desktop/Pok/pokemon.wav");
final AudioClip clip = Applet.newAudioClip(resourceUrl);
clip.loop();
}
}
Let's start with...
URL resourceUrl = new URL("file:;///C:/Users/Jack/Desktop/Pok/pokemon.wav");
Apart from the fact that there is a ;
in the path which doesn't belong, there is a simpler way to generate a URL
from a File
URL url = new File("C:/Users/Jack/Desktop/Pok/pokemon.wav").toURI().toURL();
Then move onto this...
final AudioClip clip = Applet.newAudioClip(resourceUrl);
Looking at your code, you program isn't an applet, so you really shouldn't be using Applet
based methods.
For better ways, start by taking a look at Sound Tutorial
Which might look something more like...
URL url = new File("C:/Users/Jack/Desktop/Pok/pokemon.wav").toURI().toURL();
AudioInputStream ais = AudioSystem.getAudioInputStream(url));
Clip clip = AudioSystem.getClip();
clip.open(ais);
clip.start();
clip.drain(); // Stop the main thread from exiting
This is the correct method to Open an audio clip:
public SoundClipTest() { try { URL url = this.getClass().getClassLoader().getResource("pokemon.wav"); AudioInputStream audioIn = AudioSystem.getAudioInputStream(url); Clip clip = AudioSystem.getClip(); clip.open(audioIn); clip.start(); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (LineUnavailableException e) { e.printStackTrace(); } }
Well I think there's something wrong with your url, but not sure. However you could try this to play a sound:
String mySound = "pokemon.wav";
Media media = new Media(mySound);
MediaPlayer mp = new MediaPlayer(media);
mp.play();
You should have pokemon.wav in the same folder where your java file is.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.