java - Playing music in the background of a JFrame window -


i trying play audio file in background of frame window , i'm finding out way more complicated adding picture.

i found "tutorial" should how add music , seemed simple, @ least in amount of code required. however, not able play audio file, saying 2 things...

1st - trying play audio file copied java project , telling me not find file or directory.

2nd - gave method path audio file , it's telling me...

could not audio input stream input file 

please keep in mind i'm new , tutorial did not give lot of help, not know lot of play method doing. i'd love learn how i've seen overly complicated project , don't have time put in because it's not necessary little added flair all.

any appreciated!! put stars around code in question.

public multiform() {     super("multi form program");             setlayout(new flowlayout());     menu = new jcombobox(filename);     add(menu);      /*how add background image menu.      * add(new jlabel(new imageicon(getclass().getresource("matrixpic.png"))));      */      thehandler handler = new thehandler();     menu.additemlistener(handler);   }  public void matrixpanel() {      thehandler handler = new thehandler();     //create new window when "the matrix" clicked in jcb     newframe = new jframe();     panel = new jpanel();     panel2 = new jpanel();      newframe.setlayout(new flowlayout());     newframe.setsize(500, 300);     newframe.setdefaultcloseoperation(newframe.exit_on_close);            matrixquote = new jlabel("<html><center>after this, there no turning back. "             + "<br><center>you take blue pill—the story ends, wake "             + "<br><center>in bed , believe whatever want believe."             + "<br><center>you take red pill—you stay in wonderland, , show"             + "<br><center>you how deep rabbit hole goes. "             + "<br><center>remember: i'm offering truth. nothing more.</html>");      panel.add(matrixquote);     newframe.add(panel, borderlayout.north);      //blue pill button , picture.      icon bp = new imageicon(getclass().getresource("blue pill.png"));     bluepill = new jbutton("blue pill", bp);     panel2.add(bluepill);        bluepill.addactionlistener(handler);      //red pill button , picture     icon rp = new imageicon(getclass().getresource("red pill.png"));     redpill = new jbutton("red pill", rp);     panel2.add(redpill);      newframe.add(panel2, borderlayout.center);           newframe.setvisible(true); }  ********************************************************************************* public void play(string path, int delay, int numberofloops) {     for(int = 0; < numberofloops; i++) {         new thread() {             @override             public void run() {                 try {                     file file = new file(path);                     clip clip = audiosystem.getclip();                     clip.open(audiosystem.getaudioinputstream(file));                     clip.start();                     thread.sleep(clip.getmicrosecondlength());                  } catch (exception e) {                     system.out.println(e.getmessage());                 }             }         }.start();         try {             thread.sleep(delay);         } catch (interruptedexception e) {             e.printstacktrace();         }     } } *********************************************************************************          private class thehandler implements itemlistener, actionlistener{      public void itemstatechanged(itemevent ie) {         //listen item selected.         if(ie.getstatechange() == itemevent.selected) {             object selection = menu.getselecteditem();              if("the matrix".equals(selection)) {                 matrixpanel();             }             else if("another option".equals(selection)) {                }         }        }       public void actionperformed(actionevent ae) {         if(ae.getsource() == bluepill) {             //clear panels after button clicked.             newframe.remove(panel);                      newframe.remove(panel2);             newframe.repaint();     *********************************************************************************                    play("/users/swd/downloads/fail.mp3", 10, 30);  *********************************************************************************               newframe.setsize(600, 400);             bppanellabel = new jpanel();             bplabel = new jlabel("<html><center>welcome begining of new life!  " +                      "<br><center>you're see how deep rabbit hole goes!</html>");             newframe.add(bplabel);             newframe.add(bppanellabel, borderlayout.north);             bppanelpic = new jpanel();             newframe.add(new jlabel(new imageicon(getclass().getresource("matrixpic.png"))));             newframe.add(bppanelpic, borderlayout.center);               newframe.validate();         }       }    }   //main method sets main jframe menu public static void main(string[] args) {      multiform go = new multiform();     go.setdefaultcloseoperation(jframe.exit_on_close);     go.setsize(400, 200);     go.setvisible(true); } } 

  1. java's audio api doesn't support (all) mp3 encoding. if need play mp3's should have @ javazoom's jlayer api
  2. if file trying play within project's src (or jar file extension), need use class#getresource or class#getresourceasstream instead
  3. clip auto supports looping itself, don't need use loop of own, block event dispatching thread.
  4. the thread's seem little on kill imho , while still use 1 add artificial delay, used swing timer in example, it's simpler :p

for example

import java.awt.eventqueue; import java.awt.gridbagconstraints; import java.awt.gridbaglayout; import java.awt.event.actionevent; import java.awt.event.actionlistener; import java.io.file; import java.io.ioexception; import javax.sound.sampled.audiosystem; import javax.sound.sampled.clip; import javax.sound.sampled.lineunavailableexception; import javax.sound.sampled.unsupportedaudiofileexception; import javax.swing.jbutton; import javax.swing.jfilechooser; import javax.swing.jframe; import javax.swing.jlabel; import javax.swing.joptionpane; import javax.swing.jpanel; import javax.swing.jspinner; import javax.swing.jtextfield; import javax.swing.spinnernumbermodel; import javax.swing.timer; import javax.swing.uimanager; import javax.swing.unsupportedlookandfeelexception; import javax.swing.filechooser.filefilter;  public class javaapplication5 {      public static void main(string[] args) {         new javaapplication5();     }      public javaapplication5() {         eventqueue.invokelater(new runnable() {             @override             public void run() {                 try {                     uimanager.setlookandfeel(uimanager.getsystemlookandfeelclassname());                 } catch (classnotfoundexception | instantiationexception | illegalaccessexception | unsupportedlookandfeelexception ex) {                     ex.printstacktrace();                 }                  jframe frame = new jframe("testing");                 frame.setdefaultcloseoperation(jframe.exit_on_close);                 frame.add(new testpane());                 frame.pack();                 frame.setlocationrelativeto(null);                 frame.setvisible(true);             }         });     }      public class testpane extends jpanel {          private clip clip = null;          private jtextfield audiofile;         private jbutton browse;         private jspinner loops;         private jspinner delay;         private jfilechooser chooser;          public testpane() {             setlayout(new gridbaglayout());             gridbagconstraints gbc = new gridbagconstraints();             gbc.gridx = 0;             gbc.gridy = 0;             add(new jlabel("audio file:"), gbc);              gbc.gridwidth = gridbagconstraints.remainder;             gbc.weightx = 1;             gbc.gridx++;             gbc.fill = gridbagconstraints.horizontal;             gbc.anchor = gridbagconstraints.west;             audiofile = new jtextfield(20);             add(audiofile);              gbc.gridwidth = 1;             gbc.weightx = 0;             gbc.gridx++;             browse = new jbutton("...");             add(browse, gbc);              gbc.gridx = 0;             gbc.gridy++;             add(new jlabel("loops: "), gbc);              loops = new jspinner(new spinnernumbermodel(1, 1, 100, 1));             gbc.gridx++;             gbc.fill = gridbagconstraints.none;             add(loops, gbc);              gbc.gridx = 0;             gbc.gridy++;             add(new jlabel("delay (seconds): "), gbc);              delay = new jspinner(new spinnernumbermodel(0, 0, 10, 1));             gbc.gridx++;             gbc.fill = gridbagconstraints.none;             add(delay, gbc);              gbc.anchor = gridbagconstraints.center;             gbc.gridx = 0;             gbc.gridy++;             gbc.gridwidth = gridbagconstraints.remainder;             jbutton play = new jbutton("play");             add(play, gbc);              play.addactionlistener(new actionlistener() {                 @override                 public void actionperformed(actionevent e) {                     try {                         play(                                         audiofile.gettext(),                                         (int) delay.getvalue(),                                         (int) loops.getvalue());                     } catch (lineunavailableexception | ioexception | unsupportedaudiofileexception ex) {                         ex.printstacktrace();;                         joptionpane.showmessagedialog(testpane.this, "<html>failed play audio file:</br>" + ex.getmessage(), "error", joptionpane.error_message);                     }                 }             });              browse.addactionlistener(new actionlistener() {                 @override                 public void actionperformed(actionevent e) {                     if (chooser == null) {                         chooser = new jfilechooser();                         chooser.setfileselectionmode(jfilechooser.files_only);                         chooser.setmultiselectionenabled(false);                         chooser.addchoosablefilefilter(new filefilter() {                             @override                             public boolean accept(file f) {                                 system.out.println(f);                                 return f.getname().tolowercase().endswith(".wav");                             }                              @override                             public string getdescription() {                                 return "wave files (.wav)";                             }                         });                     }                      if (chooser.showopendialog(testpane.this) == jfilechooser.approve_option) {                         file selected = chooser.getselectedfile();                         audiofile.settext(selected.getpath());                     }                 }             });          }          public void play(string path, int delay, int numberofloops) throws lineunavailableexception, ioexception, unsupportedaudiofileexception {             if (clip != null) {                 clip.stop();                 clip = null;             }              if (delay > 0) {                 system.out.println("start delay");                 timer timer = new timer(delay * 1000, new actionlistener() {                     @override                     public void actionperformed(actionevent e) {                         try {                             play(path, numberofloops);                         } catch (unsupportedaudiofileexception | lineunavailableexception | ioexception ex) {                             ex.printstacktrace();;                             joptionpane.showmessagedialog(testpane.this, "<html>failed play audio file:</br>" + ex.getmessage(), "error", joptionpane.error_message);                         }                     }                 });                 timer.setrepeats(false);                 timer.start();             } else {                 play(path, numberofloops);             }         }          private void play(string path, int numberofloops) throws unsupportedaudiofileexception, lineunavailableexception, ioexception {             file file = new file(path);             if (file.exists()) {                 clip = audiosystem.getclip();                 clip.open(audiosystem.getaudioinputstream(file));                 clip.start();             }         }     }  } 

Comments