我可以使用“play a Clip”解决方案从爪哇标签wiki页面读取和播放声音。然而,对于经常播放的声音(例如,快速激光枪声、脚步声等),每当你想要创建一个新的Clip时,打开流和重读文件对我来说都是令人不快的。因此,我试图将读取的文件缓存到byte[]中,然后从缓存中加载它们。
装载部分很容易:
// Get a BAIS.
ByteArrayInputStream bais = new ByteArrayInputStream(cache.get(fileName));
// Convert to an audio stream.
AudioInputStream ais = AudioSystem.getAudioInputStream(bais);但是,最初将文件内容放入字节数组是一个挑战。问题是,我试图从.jar中包含的文件中读取声音--因此使用java.io.File不是一个选项(据我理解),而且我看到的各种解决方案(下面的链接)也不适用。
在我看来,最困难的部分是在不使用java.io.File的情况下获取文件的长度来创建字节数组。我可以用Scanner读取字节,但我需要将它们读入数组中。我应该只使用ArrayList<Byte>吗?(见下文“次优示例”)
那么,我的问题是:byte[] 是将嵌入式文件读取到中的最佳方法,以便以后进行重复访问?
局限性
Class.getResource或Class.getResourceAsStream上。byte[]变量中。我试过什么?
我尝试使用RandomAccessFile,如下所示:
// Get the file.
RandomAccessFile f = new RandomAccessFile(fullPath, "r");
// Create a byte array.
theseBytes = new byte[(int) f.length()];
// Read into the array.
f.read(theseBytes);
// Close the file.
f.close();
// Put in map for later reference.
byteCache.put(fullPath, theseBytes);但是,显然这只适用于磁盘引用的文件;我得到以下错误:
java.io.FileNotFoundException:\path\to\sound\in\jar\file.wav (系统找不到指定的路径)
次优实例
虽然这个例子有效,但由于不断调整大小,我不认为ArrayList是最好的方法。
// Get a stream.
InputStream s = clazz.getResourceAsStream(fullPath);
// Get a byte array.
ArrayList<Byte> byteArrayList = new ArrayList<Byte>();
// Create a storage variable.
int last = 0;
// Loop.
while ((last = s.read()) != -1) {
// Get it.
byteArrayList.add((byte) last);
}
// Create a byte array.
theseBytes = new byte[byteArrayList.size()];
// Loop over each element.
for (int i = 0; i < theseBytes.length; i++) {
// Set the byte.
theseBytes[i] = byteArrayList.get(i);
}前读
发布于 2013-03-31 03:17:26
试试这个:
InputStream is = new BufferedInputStream(getClass().getResourceAsStream(name));
ByteArrayOutputStream out = new ByteArrayOutputStream();
for (int b; (b = is.read()) != -1;) {
out.write(b);
}
byte[] a = out.toByteArray();其中name是.jar中文件的路径。
https://stackoverflow.com/questions/15725871
复制相似问题