Java Exception Reading Stream from Resource .wav

删除回忆录丶 提交于 2019-12-05 20:43:46

Java Sound requires repositionable (mark/reset supported) input streams for some operations. If you strike this problem it is because the stream is not repositionable.

One way to get around it is to put the byte[] of the original stream into a ByteArrayInputStream, which supports mark/reset.


The 2nd answer on the question linked by Eric R. is also a possibility, and looks simpler. To try it, change..

InputStream is = this.getClass().getClassLoader().getResourceAsStream("beep.wav");
inputStream = AudioSystem.getAudioInputStream(is);

To:

URL url = this.getClass().getClassLoader().getResource("beep.wav");
inputStream = AudioSystem.getAudioInputStream(url);

I got the answer with the help of Tim Moores at JavaRanch. I thought the clearest thing would be to just post it here, even though Andrew mentions this correct answer in the second part of his answer. (The first part works too, but is overkill.)

Url url = this.getClass().getResource("beep.wav");           
inputStream = AudioSystem.getAudioInputStream(url);

http://www.coderanch.com/t/558274/Applets/java/mark-reset-not-supported-getResourceAsStream

Tim wrote: I have no specific knowledge about this problem, or audio in applets in general, but I'm not surprised that mark/reset doesn't work with resources obtained through the ClassLoader mechanism. (Actually, I'm sort of surprised it works at all, at least some of the time :-)

Assuming that the audio file is publicly accessible through HTTP, try AudioSystem.getAudioInputStream(URL) instead of the InputStream version you're using now. Looking at the javax.sound.sampled.spi.AudioFileReader javadocs (which is the class being used underneath), only the InputStream variant talks about mark/reset problems, not the URL version.

This also came up here: https://forums.oracle.com/forums/thread.jspa?threadID=2289395&tstart=0 and the answer is near the bottom, along with a Oracle Bug Reference #7095006 which is an interesting read as it explains why the code (as the op originally attempted) used to work but no longer does.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!