Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class BackgroundMusic extends Thread
- {
- private String fileLocation;
- private Thread t;
- private volatile boolean isPlaying;
- AudioInputStream audioInputStream;
- SourceDataLine line;
- public BackgroundMusic(String path){
- fileLocation = path;
- }
- public void play()
- {
- isPlaying = true;
- t = new Thread(this);
- t.start();
- }
- public void stopPlaying(){
- isPlaying = false;
- }
- public void run ()
- {
- while(isPlaying)
- playSound(fileLocation);
- }
- private void playSound(String fileName)
- {
- File soundFile = new File(fileName);
- audioInputStream = null;
- try
- {
- audioInputStream = AudioSystem.getAudioInputStream(soundFile);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- AudioFormat audioFormat = audioInputStream.getFormat();
- DataLine.Info info = new DataLine.Info(SourceDataLine.class,audioFormat);
- try
- {
- line = (SourceDataLine) AudioSystem.getLine(info);
- line.open(audioFormat);
- }
- catch (LineUnavailableException e)
- {
- e.printStackTrace();
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- line.start();
- int nBytesRead = 0;
- byte[] abData = new byte[128000];
- while (nBytesRead != -1 && isPlaying)
- {
- try
- {
- nBytesRead = audioInputStream.read(abData, 0, abData.length);
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- if (nBytesRead >= 0)
- {
- int nBytesWritten = line.write(abData, 0, nBytesRead);
- }
- }
- line.drain();
- line.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment