Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement background music into my Java program? [duplicate]

Tags:

java

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?


1 Answers

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.

like image 169
Ray Tayek Avatar answered Apr 03 '26 17:04

Ray Tayek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!