【发布时间】:2016-08-16 11:23:57
【问题描述】:
在 IDE 中试用我的应用程序时,我尝试从资源文件夹加载我的声音。
对于使用 InputStreams 的图像和其他内容,我使用以下方法:
@Override
public InputStream readAsset(String fileName) throws IOException {
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream(fileName);
return is;
}
这让我可以打开一个输入流,我可以从中提取图像。
一旦我尝试将此 InputStream 转换为音频 InputStream,就会出现错误。另外,如果我尝试制作一个新的 AudioInputStream,将上面的 InputStream 作为参数传递。
这是我目前从外部路径加载声音的方式:
public class JavaSound implements Sound {
private Clip clip;
public JavaSound(String fileName){
try {
File file = new File(fileName);
if (file.exists()) {
//for external storage Path
AudioInputStream sound = AudioSystem.getAudioInputStream(file);
// load the sound into memory (a Clip)
clip = AudioSystem.getClip();
clip.open(sound);
}
else {
throw new RuntimeException("Sound: file not found: " + fileName);
}
}
catch (MalformedURLException e) {
e.printStackTrace();
throw new RuntimeException("Sound: Malformed URL: " + e);
}
catch (UnsupportedAudioFileException e) {
e.printStackTrace();
throw new RuntimeException("Sound: Unsupported Audio File: " + e);
}
catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("Sound: Input/Output Error: " + e);
}
catch (LineUnavailableException e) {
e.printStackTrace();
throw new RuntimeException("Sound: Line Unavailable Exception Error: " + e);
}
}
@Override
public void play(float volume) {
// Get the gain control from clip
FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
// set the gain (between 0.0 and 1.0)
float gain = volume;
float dB = (float) (Math.log(gain) / Math.log(10.0) * 20.0);
gainControl.setValue(dB);
clip.setFramePosition(0); // Must always rewind!
clip.start();
}
@Override
public void dispose() {
clip.close();
}
}
如何交换 AudioInputStream 部分,使其像第一个代码一样工作,将文件从我的资源目录中拉出?
编辑: 这种通过传递 InputStream 来创建新的 AudioInputStream 的方式
File file = new File(fileName);
if (file.exists()) {
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream(fileName);
//for external storage Path
AudioInputStream sound = new AudioInputStream(is);
// load the sound into memory (a Clip)
clip = AudioSystem.getClip();
clip.open(sound);
}
在运行之前也会抛出错误
【问题讨论】:
-
我没有看到只接受输入流的
AudioInputStream的构造函数。 This Javadoc 表示选项为AudioInputStream(InputStream stream, AudioFormat format, long length)或AudioInputStream(TargetDataLine line)。AudioSystem.getAudioInputStream(InputStream stream)方法似乎只采用输入流(如答案中所建议的那样)。但是,请注意 Javadocs 中的限制。 -
大声笑我怎么知道帧的长度...这有多烦人? AudioSystem.getAudioInputStream(InputStream stream) 这不起作用!它会引发运行时错误
标签: java audio resources inputstream audioinputstream