문제

The following code runs, but prints null. The end goal is to have the song play, and be able to stop it by pressing the cancel button. Any ideas? Thanks..

Here is my code:

if (song.equals("Dan + Shay - 19 You + Me")){//if this song is selected...
        try{
            stopPlay();
            AudioInputStream audio = AudioSystem.getAudioInputStream(getClass().getResourceAsStream("C:\\Stuff\\Grade Twelve\\Computer Programming\\Unit 4\\Step 3\\GuitarForBeginners\\src\\guitarforbeginners\\resources\\You+Me.wav"));
            clip = AudioSystem.getClip();
            clip.open(audio);
            clip.start();
        } catch(Exception e){
            stopPlay();
            System.err.println(e.getMessage());
}
도움이 되었습니까?

해결책

I think the problem might be with how you are addressing your audio file. Since you have a complete path, you can just put in the file location and dispense with the part "getClass().getResourceAsStream()".

The spec for this form of getAudioInputStream() is at the following URL: getAudioInputStream(File file)

I think getResource() and getResourceAsStream() are more apt for loading resources packed in a jar file, where you need to know and make use of the file location or URL of the jar. AFAIK, by using getResource(String name) and getResourceAsStream(String name), you are automatically prefixing the file location of the host object in front of the specified string "name", creating a very tangled filename. The term "absolute" used in the spec for these methods refers to the absolute location of the host object. There is some information on how addresses are constructed in the specs for getResourceAsStream(String name) and getResource(String name).

One other precaution (thanks Andrew for pointing this out): if you do have a situation where you need to use the address of the class file as an anchor or starting point, it is probably safer with audio files to use getResource(String name) than getResourceAsStream(String name). The latter returns an InputStream, and InputStreams may have checks for the ability to Mark or Reset the stream. Audio files don't seem to always have this capability and can thus throw errors. getResource(String name) returns a URL, and the URL can be used as the input parameter to getAudioInputStream(URL url), circumventing the use of InputStream.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top