3
import sun.audio.*;
import java.io.*;
public class musicTest
{
   public static void main(String[] args)
   {
   try
   {
      InputStream in = new FileInputStream("musicFile.mp3");
      AudioStream as = new AudioStream(in);
      AudioPlayer.player.start(as);
   }
   catch(FileNotFoundException e)
   {
      System.out.println("File does not exist or could not be found.");
      System.out.println("FileNotFoundException: " + e.getMessage());
   }
   catch(IOException e)
   {
      System.out.println("Problem reading file.");
      System.out.println("IOException: " + e.getMessage());
   }
   }
}

When I try compiling the program, it says, "AudioStream is internal proprietary API and may be removed in a future release... AudioPlayer is internal proprietary API and may be removed in a future release..."

How do I fix this?

  • 2
    You should make use of the `Clip` class, for [example](http://stackoverflow.com/questions/22469164/playing-wav-file-in-java-from-file-from-computer/22469341#22469341), [example](http://stackoverflow.com/questions/21146973/starting-and-stopping-music-in-background/21147304#21147304), [example](http://stackoverflow.com/questions/27643416/how-to-repeat-audio-file-in-java/27643431#27643431), [example](http://stackoverflow.com/questions/30823537/sound-problems-in-java/30835694#30835694). Remember, though, this starts a (I believe) daemon thread, which will stop when the JVM exist – MadProgrammer Jan 19 '16 at 22:10

1 Answers1

1

try something like this:

    String filename="foo.wav";
    Clip clip=AudioSystem.getClip();
    AudioInputStream inputStream=AudioSystem.getAudioInputStream(new BufferedInputStream(Audio.class.getResourceAsStream(filename)));
    if(inputStream!=null) {
        clip.open(inputStream);
        FloatControl gainControl=(FloatControl)clip.getControl(FloatControl.Type.MASTER_GAIN);
        gainControl.setValue(+6.0f); // ?
        clip.start();
        // maybe do not wait?
        while(clip.getMicrosecondLength()!=clip.getMicrosecondPosition())
            Thread.yield(); // wait
        // or at least don't wait here?
        Thread.sleep(500);
        clip.close();
    }

works on windows 8.1

be sure that the wave file is the same directory as the class that has the code and make sure it's on the classpath.

also, you probably want to do this on a separate thread.

Ray Tayek
  • 9,841
  • 8
  • 50
  • 90
  • I'm new to Java! I'm sorry, but this code is really difficult to understand! Is there a simpler way to implement music into a Java-based program? I just want to play a '.wav' file as soon as the program runs –  Jan 20 '16 at 01:24
  • i think you need to do something similar. see: http://stackoverflow.com/questions/26305/how-can-i-play-sound-in-java, https://www.youtube.com/watch?v=QVrxiJyLTqU – Ray Tayek Jan 20 '16 at 02:52