如何使用Java播放WAV文件?
我使用客户端和服务器发送WAV文件,但我想在收到WAV文件时播放它。我尝试了这种方法,但不起作用:如何使用Java播放WAV文件?,java,Java,我使用客户端和服务器发送WAV文件,但我想在收到WAV文件时播放它。我尝试了这种方法,但不起作用: Runtime.getRuntime().exec("C:\\Documents and Settings\\Administratore\\Desktop\\gradpro\\test1\\s1.wav") ; 这是我得到的例外: 错误!没用!java.io.IOException:无法运行程序C:\Documents:CreateProcess error=193,%1不是有效的Win3
Runtime.getRuntime().exec("C:\\Documents and Settings\\Administratore\\Desktop\\gradpro\\test1\\s1.wav") ;
这是我得到的例外:
错误!没用!java.io.IOException:无法运行程序C:\Documents:CreateProcess error=193,%1不是有效的Win32应用程序
我做错了什么?您需要执行音频播放器程序,可能是windows media player或类似的程序,然后将文件名和文件的完整路径作为参数传入:
String wavPlayer = "/path/to/winmediaplayer.exe";
String fileToPlay = "/path/to/wav/file.wav";
Runtime.getRuntime().exec(wavPlayer, new String[]{fileToPlay}) ;
那应该行。试试:
Runtime.getRuntime().exec("'C:\Documents and Settings\Administratore\Desktop\gradpro\test1\s1.wav'") ;
注意额外的单引号。我甚至不确定你的方法是否有效,但试试看 是否必须使用默认音频播放器?
如果没有,您可能希望查看Java的。让windows为您查找,而不是指定要使用的媒体播放器:
String comspec = System.getenv().get("ComSpec");
String fileToPlay = "/path/to/wav/file.wav";
Runtime.getRuntime().exec(comspec, new String[]{"/c", "start", fileToPlay}) ;
你基本上是在做这样的事情:
cmd.exe /c start path_to_wav_file.wav
要查看start提供的所有选项,start是cmd.exe的内置操作,而不是独立程序,这就是为什么必须运行cmd.exe而不是“start.exe”的原因
start /h
Java内置的WAV播放支持有什么问题?您可以使用音频剪辑播放:
private void playBackClip(String fileName) {
try {
AudioInputStream soundStream = null;
if (fileName.startsWith("res:")) {
soundStream = AudioSystem.getAudioInputStream(
Object.class.getResourceAsStream(fileName.substring(4)));
} else {
File audioFile = resMap.get(fileName);
soundStream = AudioSystem.getAudioInputStream(audioFile);
}
AudioFormat streamFormat = soundStream.getFormat();
DataLine.Info clipInfo = new DataLine.Info(Clip.class,
streamFormat);
Clip clip = (Clip) AudioSystem.getLine(clipInfo);
soundClip = clip;
clip.open(soundStream);
clip.setLoopPoints(0, -1);
clip.start();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
老问题,但记录在案:
java.awt.Desktop.getDesktop().open(new java.io.File(my_filename));
这是不对的。海报需要运行适当的程序,然后将文件作为参数传入。Java Sound程序员指南中有更多信息: