I have a problem with selecting a wav. near is code:
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"mp3 & wav Images", "wav", "mp3");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(getParent());
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName());
}
InputStream in = new FileInputStream(chooser.getSelectedFile().getAbsolutePath());
AudioStream as = new AudioStream(in);
AudioPlayer.player.start(as);
I got error in eclipse for AudioStream and AudioPlayer, i use JDK 7. How to solve the problem?
This SSCCE works for me. I'm running jdk 1.7.0_45 on linux. I tested it with the file
/usr/lib/libreoffice/share/gallery/sounds/train.wav
Main.java
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.FileInputStream;
import java.io.InputStream;
/**
* http://stackoverflow.com/questions/20639187/jfilechooser-select-audio-wav-java
*/
public class Main {
public static void main(String[] args) throws Exception {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new FileNameExtensionFilter("mp3 & wav Images", "wav", "mp3"));
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
InputStream in = new FileInputStream(chooser.getSelectedFile().getAbsolutePath());
AudioStream as = new AudioStream(in);
AudioPlayer.player.start(as);
}
// Move the code that was here, to play the file, inside the if statement so the
// application doesn't crash if the user doesn't select a file to play.
}
}
You can test it from the command line with the following:
javac Main.java
java Main
In the code that you posted, you would have gotten a runtime error if you didn't select a file from the JFileChooser because you're trying to access the selected file even if the user doesn't choose one.
Try the following snippet, that worked for me several times:
...
URL url = ClassLoader.getResource(chooser.getSelectedFile().getAbsolutePath());
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
Clip clip = AudioSystem.getClip();
clip.open(ais);
...
also discussed in How to cast from InputStream to AudioInputStream
btw: your code works fine on my machine...
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.