在IDE中试用我的应用程序时,我尝试从资源文件夹中加载声音。
对于使用InputStreams的图像和其他东西,我使用以下方法:
@Override
public InputStream readAsset(String fileName) throws IOException {
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream(fileName);
return is;
}
这使我可以打开一个Inputstream,其中可以拉入图像。
一旦我尝试将此InputStream强制转换为Audio InputStream,我就会收到错误消息。另外,如果我尝试通过上述InputStream作为参数来制作一个新的AudioInputStream。
这是我目前从外部路径加载声音的方式:
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);
}
在运行之前也抛出错误
最佳答案
您不能将InputStream
转换为AudioInputStream
(可以执行相反的操作)。 Clip.open()
需要一个AudioInputStream。
建议的方法by this answer here是使用.getResource()
调用中的URL,而不是尝试打开InputStream然后将其传递进来。
因此,请尝试:
URL soundURL = classloader.getResource(fileName);
AudioInputStream ais = AudioSystem.getAudioInputStream(soundURL);
关于java - InputStream的AudioInputStream(从资源目录加载),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36800437/