I put this right after I listed my imports, there are no errors but when I click run my interface shows up but there is no audio. I have the .wav file in the src directory and I've placed it in every folder once but still when I click run there is no audio. Assistance would be very appreciated.
public class Mygame extends javax.swing.JFrame {
private Clip music;
private void startSong(){
try{
AudioInputStream stream = AudioSystem.getAudioInputStream(getClass().getResource("gamemusic.wav"));
music = AudioSystem.getClip();
music.open(stream);
music.start();
}
catch(Exception e){
music = null;
}
}
If you are using netbeans then paste your wav file in Files tab beside project tab at left top corner.
Related
I'm trying to get file (readme.txt) from my project folder. Don't know how to get location of project. When I say project, I mean location where my application code is written and not runtime application. I've tried getting absolute path, relative path... and it always gives me folder of runtime application. Also tried something like this.getClass() and tried to extract path or System.getProperty("user.dir"). These two also gives me path of my eclipse.../.../...runtime app. I'm making eclipse plugin, and this file is suppose to be part of my plugin, so that when user click's on button, this file opens (it's some help txt file). This is my code for opening file, problem is path.
/**
* Help button listener. If button is pressed, help file is opened.
*/
private void listenButtonHelp() {
buttonHelp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (Desktop.isDesktopSupported()) {
File helpFile = new File("\\readme.txt");
helpFile.setReadOnly();
Desktop desktop = Desktop.getDesktop();
try {
desktop.open(helpFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
It depends on where exactly the file is in your project. A clean point to put it might be ${project.root}/resources, so create a folder and put the file there. Mark it as a "source folder" in Eclipse (project properties -> build path -> source folders). Your current setup isn't a good idea because the file will not be included in your distribution by Eclipse's compile.
Now, when you compile the code, this gets copied into the target directors (bin per default); you can check by opening it in your file browser.
So to check the file is there, you can do
Path filePath = Paths.get("resources", "readme.txt");
System.out.println(Files.exists(filePath));
If you need it as a File, you can do
File readmeFile = filePath.toFile();
This reads the file from the source project folder, so it won't be much use after you run the program somewhere else.
For that, you can use the ClassLoader:
URL readmeUrl = ClassLoader.getSystemClassLoader().getResource("resources/readme.txt"));
File readmeFile = new File(readmeUrl.getFile());
I found answer, this works for me:
/**
* Help button listener. If button is pressed, help file is opened.
*/
private void listenButtonHelp() {
buttonHelp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (Desktop.isDesktopSupported()) {
File file = null;
Bundle bundle = Platform.getBundle("TestProject");
IPath path = new Path("resources/readme.txt");
URL url = FileLocator.find(bundle, path, null);
/*
* After FileLocator, I get also this, like I commented before:
* D:\\eclipse-rcp-oxygen\\eclipse\\..\\..\\..\\eclipse_oxygen_workspace\\
* TestProject\\resources\\readme.txt and before it didn't work but if
* you add these lines:
* url = FileLocator.toFileURL(url);
* file = URIUtil.toFile(URIUtil.toURI(url));
* Like in my try bracket, it works. I guess it needs to be
* converted using URIUtil.
* Now it finds file, and it can be opened, also works for .html files.
*/
Desktop desktop = Desktop.getDesktop();
try {
url = FileLocator.toFileURL(url);
file = URIUtil.toFile(URIUtil.toURI(url));
// file.setReadOnly();
desktop.open(file);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
});
}
I did this small Java project that in it's turn opens different MP3 files. For that I downloaded the JLayer 1.0.1 library and added it to my project. I also added the MP3 files to a package on my project -as well as some JPG images- so as to obtain them from there, and I'm using a hashmap (mapa) and this method to get them:
public static String consiguePath (int i) {
return AppUtils.class.getClass().getResource("/Movimiento/" + mapa.get(i)).getPath();
}
so as to avoid absolute paths.
When I open an MP3 file I do this:
try {
File archivo = new File(AppUtils.consiguePath(12));
FileInputStream fis = new FileInputStream(archivo);
BufferedInputStream bis = new BufferedInputStream(fis);
try {
Player player = new Player(bis);
player.play();
} catch (JavaLayerException jle) {
}
} catch (IOException e) {
}
The whole thing runs perfectly in NetBeans, but when I build a .jar file and execute it it runs well but it won't open the MP3 files. What called my attention is that it doesn't have trouble in opening the JPG files that are on the same package.
After generating the .jar I checked the MyProject/build/classes/Movimiento folder and all of the MP3 files were actually there, so I don't know what may be happening.
I've seen others had this problem before but I haven't seen any satisfactory answer yet.
Thanks!
Change the consiguePath to return the resulting URL from getResource
public static URL consiguePath(int i) {
return AppUtils.class.getClass().getResource("/Movimiento/" + mapa.get(i));
}
And then use it's InputStream to pass to the Player
try {
URL url = AppUtils.consiguePath(12);
Player player = new Player(url.openStream());
player.play();
} catch (JavaLayerException | IOException e) {
e.printStackTrace();
}
Equally, you could just use Class#getResourceAsStream
Resources are packaged into your Jar file and can no longer be treated as Files
I created a project that plays audio within the netbeans IDE. Those audio files were placed in the Classes folder.
Although when I created it as a JAR file, it was unable to locate the audio files. I even copy and pasted the files inside the new dist folder.
Here is a snippet of code:
private void playSound39()
{
try
{
/**Sound player code from:
http://alvinalexander.com/java/java-audio-example-java-au-play-sound
*/
// the input stream portion of this recipe comes from a javaworld.com article.
InputStream inputStream = getClass().getResourceAsStream("./beep39.wav");
AudioStream audioStream = new AudioStream(inputStream);
AudioPlayer.player.start(audioStream);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,"Audio file not found!");
}
}
If you want to embedd the audio file in your program it's must be placed inside the src folder in a package.
For example I'll demonstrate a code I use to set icons to buttons (should work for audio files as well) :
While creating the JFrame I wrote :
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Icon/PatientBig.png")));
I have in my project a package called GUI with a subpackage called Icons where my icons exist and they all are in src folder.
When you using getClass().getResource function , I prefer to use an absolute path.
After seeing your respone I have noticed that you keep using . in the begining of the class path, I copied the snippet you published and removed the . from the begining of the path and placed my audio file bark.wav in the src folder in the default package and it worked
public class test {
private void playSound39() {
try {
/**
* Sound player code from:
* http://alvinalexander.com/java/java-audio-example-java-au-play-sound
*/
// the input stream portion of this recipe comes from a javaworld.com article.
InputStream inputStream = getClass().getResourceAsStream("/bark.wav");
AudioStream audioStream = new AudioStream(inputStream);
AudioPlayer.player.start(audioStream);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Audio file not found!");
}
}
public static void main(String[] args){
new test().playSound39();
}
}
Then I placed the audio file inside a package called test1 and modified the path in getResourceAsStream function and again it worked:
public class test {
private void playSound39() {
try {
/**
* Sound player code from:
* http://alvinalexander.com/java/java-audio-example-java-au-play-sound
*/
// the input stream portion of this recipe comes from a javaworld.com article.
InputStream inputStream = getClass().getResourceAsStream("/test1/bark.wav");
AudioStream audioStream = new AudioStream(inputStream);
AudioPlayer.player.start(audioStream);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Audio file not found!");
}
}
public static void main(String[] args){
new test().playSound39();
}
}
The Most important thing is to remove . from the path
try this
InputStream in = getClass().getResourceAsStream("/beep39.wav");
I think you need to bypass use of the InputStream. When running the getAudioInputStream method, using InputStream as a parameter triggers markability and resetability tests on the audio file. Audio files usually fail these tests. If you create your AudioInputStream with a URL or File parameter, these tests are circumvented. I prefer URL as it seems more robust and can "see into" jars.
URL url = getClass().getResource("./beep39.wav");
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
Then, in a while loop, you would execute a read method on the AudioInputStream and send the data to a SourceDataLine.
The Java Tutorials covers this in their audio trail. This link jumps into the middle of the tutorials.
AFAIK, there is no "AudioPlayer" in the Java 7 SDK.
So what I have tried to do is make my application play music in the background with a .wav music file.
I have this code but AudioStream can't be found under
sun.audio.*;
If any of you have worked with Eclipse IDE, how would you be able to find AudioStream to import it...
Here's my code which this uses. It's under the Sound class which doesn't implement or extend anything.
private AudioStream as;
private String lastSoundPath;
private void setStream(String soundPath){
this.lastSoundPath = soundPath;
try {
InputStream in = new FileInputStream(soundPath);
this.as = new AudioStream(in);
} catch (Exception e) {
e.printStackTrace();
}
}
Here's the error I get when trying to play Bangarang (Random I know...)
java.io.IOException: could not create audio stream from input stream
at sun.audio.AudioStream.<init>(AudioStream.java:82)
at vapour.studios.destiny.client.Sound.setStream(Sound.java:17)
at vapour.studios.destiny.client.Sound.<init>(Sound.java:24)
at vapour.studios.destiny.Destiny.main(Destiny.java:23)
Thanks in advance.
You need to use javaSE 1.7 as execution environment in project properties.
it worked for me on Mac OS 10.8
I'm making a program, and I want it to start playing sounds when it opens. I figured the easiest way for me to do this is to embed the .wav file in the src folder in my jar. I have placed the file in a packaged called files and all the other files i am using such as pictures are in that package and they all work fine. my method for playing sounds is here:
public static void playSound(String dir, int loopTimes) throws Exception {
URL url = new File(dir).toURI().toURL();
Clip clip = AudioSystem.getClip();
// getAudioInputStream() also accepts a File or InputStream
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
clip.open(ais);
if (loopTimes == -1)
loopTimes = Clip.LOOP_CONTINUOUSLY;
clip.loop(loopTimes);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
}
});
}
and it works for playing the sounds when they are on my desktop, my documents, anywhere else. the path that i am inputting for playing the sound is "files/FBP.wav" were FBP is the name of the file. i havent been able to find any solutions on google, and i have the feeling that it is because it is in the JAR. I have also just simply tried this:
if(new File("files/FBP.wav").exists()){
System.out.println("EXISTS!");
}
System.exit(0);
and it never printed out that it exists. i have made sure that it is in the bin folder as well. i am using eclipse. the error i get is filenotfoundexception. any help is appreciated! Thanks in advance!
Replace:
URL url = new File(dir).toURI().toURL();
With:
URL url = MySoundClassName.class.getClassLoader().getResource(dir);
Or for non-static methods:
URL url = getClass().getClassLoader().getResource(dir);