-2

I have question. I have program where I need to play music in background. Can someone help me? I already searched on internet but no solution worked for me.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Flopflak
  • 1
  • 1
  • 2
  • 2
    What have you tried so far? – Martin H. May 01 '21 at 17:39
  • Welcome to Stack Overflow. Please take the [tour] to learn how Stack Overflow works and read [ask] on how to improve the quality of your question. Then check the [help/on-topic] to see what questions you can ask. Please see: [Why is “Can someone help me?” not an actual question?](https://meta.stackoverflow.com/q/284236). Please show your attempts you have tried and the problems/error messages you get from your attempts. – Progman May 01 '21 at 17:41
  • I tried this https://stackoverflow.com/questions/13573281/how-to-play-a-background-music-when-the-program-run-in-java and then i just found same method as this but nothing worked, then i tried lot of youtube tutorials but nothing worked too – Flopflak May 01 '21 at 17:52
  • 2
    Add your own non-working code please – Tarmo May 01 '21 at 18:11
  • I have made a game in Java sometime ago in which I there is a background music you can find the project in my github repos: https://github.com/syedMohib44/Games-on-Java-and-Misc-Projects/tree/master/WreckIt%20Ralph/src – Syed Mohib Uddin May 01 '21 at 18:27
  • Thanks, code from your github worked. – Flopflak May 01 '21 at 21:33

1 Answers1

0

Imports:

import java.io.File; 
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

Code:

try //playing the music
{
    String soundName = "yourAudioFile.wav";    
    AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(soundName).getAbsoluteFile());
    Clip clip = AudioSystem.getClip();
    clip.open(audioInputStream);
    clip.start(); //start to play the clip
} 
catch (Exception e) 
{
    //Do stuff in case of an exception, for example, file not found
}
TheSj
  • 376
  • 1
  • 11