在 IDE 中试用我的应用程序时,我尝试从资源文件夹中加载我的声音。
对于使用 InputStreams 的图像和其他内容,我使用此方法:
@Override
public InputStream readAsset(String fileName) throws IOException {
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream(fileName);
return is;
}
这让我可以打开一个输入流,我可以从中提取图像。
一旦我尝试将此 InputStream 转换为 Audio 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);
}
甚至在运行它之前也会抛出错误