2

I'm trying to play music in the background of my game, and I want to make it loop, i'm getting this error

java.io.IOException: could not create audio stream from input stream

I've tried using .getResourceAsStream, but it returns null, probably because it requires a URL so I'm probably doing something wrong with that

I've also tried using this.getClass().getClassLoader().getResource but that produces a bunch of runtime errors.

This is the code for the music part of the program. I've confirmed that the button works, clicking it just returns that IOException that I mentioned above.

public static void music(){
    AudioPlayer AP = AudioPlayer.player;
    AudioStream AS;
    AudioData AD;
    ContinuousAudioDataStream loop = null;

    try{
        AS = new AudioStream(new FileInputStream("theme.mp3"));
        AD = AS.getData();
        loop = new ContinuousAudioDataStream(AD);
    }catch(IOException error){
        System.out.println(error);
    }
    AP.start(loop);
}
Lino
  • 19,604
  • 6
  • 47
  • 65
EkLuthra
  • 147
  • 1
  • 9
  • 2
    Since @second doesn't have enough rep to comment, here's their question: "Where is your file "theme.mp3" located? I assume it can't find the file ... Also add the full exception stracktrace to your question." – Federico klez Culloca May 17 '19 at 13:20
  • 1
    Also, post complete, executable code. By the way, when I replace "theme.mp3" with ""C:/Windows/media/tada.wav", it works fine. – hfontanez May 17 '19 at 13:34
  • 1
    The 'sun.audio.*' classes are not part of the official Java API and don't exist at all in current versions of Java. Use the 'javax.sound.xxx' APIs, see for example [here](https://stackoverflow.com/a/27344215/2670892) – greg-449 May 17 '19 at 13:36
  • 1
    Please **at least** post your imports and add the tag *android*, if it's not the regular JDK. – Hendrik May 17 '19 at 14:15
  • In Java, URL url = this.getClass().getResource("theme.mp3"); works fine (assumes file is in same folder as the invoking class). But javax.sound.sampled doesn't have a provision for decoding mp3's, so it is hard to tell what the context is and what is going on. Are the various AudioXXX classes ones that you wrote? They aren't part of javax.sound.sampled. – Phil Freihofner May 17 '19 at 20:19
  • Java Sound supports various formats via a Service Provider Interface out of the box. MP3 is ***not*** one of them. An SPI for MP3 can be obtained from JMF, if you're lucky enough to find a copy of it somewhere. – Andrew Thompson May 18 '19 at 00:25

0 Answers0