2012-07-16 58 views
2

我尝试使用Java播放声音时遇到问题;如果我使用使用FileInputStream时发生Java UnsupportedAudioFileException

AudioInputStream soundIn = AudioSystem.getAudioInputStream(new File("./sound.wav")); 

获取AudioInputStream,它的工作原理和文件播放正常。但是,如果我用

AudioInputStream soundIn = AudioSystem.getAudioInputStream(new BufferedInputStream(new FileInputStream("./sound.wav"))); 

我得到

javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input stream 

我所试图做的是回放,我已经从麦克风录制的音频,我把它保存为一个WAV文件在内存中的字节数组,我不能玩它。但是,如果我将它保存到文件并直接使用File对象,它就会播放。但是,如果使用任何形式的InputStream的,它失败,除此之外,包括当我使用此代码:

AudioInputStream soundIn = AudioSystem.getAudioInputStream(new BufferedInputStream(new ByteArrayInputStream(recorder.getLastRecording()))); 

凡recorder.getLastRecording()返回一个字节数组。有任何想法吗?

回答

1
// lose the BufferedInputStream 
AudioInputStream soundIn = AudioSystem.getAudioInputStream(
    new ByteArrayInputStream(recorder.getLastRecording())); 
1

这个错误实际上已经以各种伪装出现过无数次了。

我在想什么是每当您尝试使用InputStream或使用需要InputStream作为中间步骤之一的代码时,Java会测试该文件是否作为InputStream有效:它是否支持“标记“是一个这样的测试,也是该文件是否是”可复位“的。

请注意,您的错误消息表示无法从InputStream获取有效文件。这可能是因为Java无法在文件上执行一个或其他命令,因此不会将其视为有效的InputStream。

如果您从File位置或更好的URL(imho)打开文件,则AudioSystem.getAudioInputStream不会经过测试的中间步骤,如果该文件可以用作有效的InputStream。

其实,下面的javadef支持我说得很清楚。

http://docs.oracle.com/javase/6/docs/api/javax/sound/sampled/AudioSystem.html#getAudioInputStream(java.io.InputStream

请注意,如果你比较各种形式的“getAudioInputStream”,你会看到有关于相较于URL和文件参数版本InputStream的参数版本的文件额外的要求。

我喜欢使用最好的URL,因为URL可以很好地在jar文件中定位文件,并且可以指定资源与代码或类的根目录相关联。

相关问题