本文介绍了如何从InputStream中转换为的AudioInputStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能从InputStream转换为的AudioInputStream?

Is it possible to cast from an InputStream to an AudioInputStream?

我想在某些活动中发挥一点声音文件,所以我做了以下SoundThread

I want to play little sound files at certain events, so I made following SoundThread

import java.io.*;
import javax.sound.sampled.*;

public class SoundThread implements Runnable{

    private String filename;

    SoundThread(String filename) {
        this.filename = filename;
    }

    public void run() {
        try {
            InputStream in = ClassLoader.getSystemResourceAsStream("sounds/"+filename+".wav");
            Clip clip = AudioSystem.getClip();
            clip.open((AudioInputStream)in);
            clip.start();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (LineUnavailableException e){
            e.printStackTrace();
        } 
    }
}

我和运行它。

new Thread(new SoundThread("nameOfTheSoundFile")).start();

在开始的时候我的sun.audio.AudioPlayer和sun.audio.AudioStream处理它,但只要我把那个code在Eclipse中,它给我的错误。所以,我想

At the beginning I handled it with the sun.audio.AudioPlayer and sun.audio.AudioStream, but as soon I put that code in eclipse, it showed me errors. So I tried

AudioInputStream in = (AudioInputStream)ClassLoader.getSystemResourceAsStream("sounds/"+filename+".wav");

要InputStream的转换为的AudioInputStream(日食并没有表现出任何错误),但它运行它抛出一个ClassCastException异常。是否有此问题的任何解决方案?

to cast the InputStream to AudioInputStream (eclipse didn't show any errors), but running it it throws an ClassCastException. Is there any solution for this problem?

推荐答案

使用 AudioSystem 来获得的AudioInputStream 直接从网​​址的资源。

Use the AudioSystem to get an AudioInputStream directly from the URL to the resource.

URL url = ClassLoader.getResource("/sounds/"+filename+".wav");
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
Clip clip = AudioSystem.getClip();
clip.open(ais);

又见<$c$c>AudioSystem.getAudioInputStream(InputStream)但这是更加危险。 Java的声音通常需要一个可重新定位的输入流。出于某种原因,我不上了,在 Class.getResourceAsStream()变种有时返回的 -repositionable流。

See also AudioSystem.getAudioInputStream(InputStream) but this is 'more dangerous'. Java Sound will typically require a repositionable input stream. For some reason that I am not quite clear on, the Class.getResourceAsStream() variants sometimes return a non-repositionable stream.

这篇关于如何从InputStream中转换为的AudioInputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 00:26