Page 1 of 2 12 LastLast
Results 1 to 20 of 35
Like Tree1Likes

Thread: Mp3 in background?

  1. #1
    seegee is offline Member
    Join Date
    Jul 2011
    Posts
    36
    Rep Power
    0

    Default Mp3 in background?

    Ok, so i am making this program and I am trying to get an MP3 to play in the background. I am just a beginner and I thought it would be simple but I have been searching for over an hour and cant seem to find anything understandable. Right now I am using this code in my main method:
    Java Code:
      AudioPlayer AP= AudioPlayer.player;
            AudioStream AS;
            AudioData AD;
            ContinuousAudioDataStream loop= null;
            
            try {
            AS= new AudioStream(new FileInputStream("glass_shatter_c.wav"));
            AD= AS.getData();
            loop= new ContinuousAudioDataStream (AD);
            }catch (IOException error) {}
            
            
           AP.start (loop);


    Here is the whole code:
    Java Code:
    import sun.audio.*;
    import java.io.*;
    
    
    public class MEFIRST extends javax.swing.JFrame {
    
        /** Creates new form MEFIRST */
        public MEFIRST() {
            initComponents();
        }
        
       
    
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
    
            jButton1 = new javax.swing.JButton();
            DPW = new javax.swing.JTextField();
            PPH = new javax.swing.JTextField();
            HPD = new javax.swing.JTextField();
            PPHL = new javax.swing.JLabel();
            HPDL = new javax.swing.JLabel();
            DPWL = new javax.swing.JLabel();
            TITLE = new javax.swing.JLabel();
            PPD = new javax.swing.JLabel();
            PPW = new javax.swing.JLabel();
            PPY = new javax.swing.JLabel();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Celcious");
            setBackground(new java.awt.Color(0, 204, 0));
    
            jButton1.setText("Ok");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
    
            PPH.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    PPHActionPerformed(evt);
                }
            });
    
            PPHL.setForeground(new java.awt.Color(255, 255, 51));
            PPHL.setText("Pay Per Hour");
    
            HPDL.setForeground(new java.awt.Color(255, 255, 51));
            HPDL.setText("Hours Per Day");
    
            DPWL.setForeground(new java.awt.Color(255, 255, 51));
            DPWL.setText("Days Per Week");
    
            TITLE.setFont(new java.awt.Font("PortagoITC TT", 1, 74)); // NOI18N
            TITLE.setForeground(new java.awt.Color(51, 102, 255));
            TITLE.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            TITLE.setText("CJ's Money Machine!");
    
            PPD.setForeground(new java.awt.Color(255, 0, 0));
            PPD.setText("Pay Per Day:");
    
            PPW.setForeground(new java.awt.Color(255, 0, 0));
            PPW.setText("Pay Per Week:");
    
            PPY.setForeground(new java.awt.Color(255, 0, 0));
            PPY.setText("Pay Per Year:");
    
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                                .add(DPWL)
                                .add(PPHL)
                                .add(HPDL))
                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                                .add(org.jdesktop.layout.GroupLayout.LEADING, PPH, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE)
                                .add(HPD)
                                .add(org.jdesktop.layout.GroupLayout.LEADING, DPW))
                            .add(54, 54, 54)
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                .add(PPD)
                                .add(PPW)
                                .add(PPY))
                            .add(78, 78, 78))
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                            .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 230, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(145, 145, 145))
                        .add(layout.createSequentialGroup()
                            .add(TITLE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 502, Short.MAX_VALUE)
                            .addContainerGap())))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(34, 34, 34)
                    .add(TITLE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 70, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(PPH, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(PPHL)
                        .add(PPD))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(HPD, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(HPDL, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 16, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(PPW))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(DPW, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(DPWL)
                        .add(PPY))
                    .add(18, 18, 18)
                    .add(jButton1)
                    .addContainerGap(41, Short.MAX_VALUE))
            );
    
            pack();
        }// </editor-fold>
    
        private void PPHActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
        }
    
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    
        double PayPerHour= (double)((Double.parseDouble(PPH.getText())));
        double HoursADay=(double)((Double.parseDouble(HPD.getText())));
        double DaysAWeek=(double)((Double.parseDouble(DPW.getText())));
        double PerDay= PayPerHour*HoursADay;
        double PerWeek= PerDay*DaysAWeek;
        double PerYear= PerYear= PerWeek*52;
        PPD.setText("Pay Per Day: " +PerDay );
        PPW.setText("Pay Per Week: " +PerWeek );
        PPY.setText("Pay Per Year: " +PerYear );
        }
    
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
              AudioPlayer AP= AudioPlayer.player;
            AudioStream AS;
            AudioData AD;
            ContinuousAudioDataStream loop= null;
            
            try {
            AS= new AudioStream(new FileInputStream("glass_shatter_c.wav"));
            AD= AS.getData();
            loop= new ContinuousAudioDataStream (AD);
            }catch (IOException error) {}
            
            
           AP.start (loop);
            
            java.awt.EventQueue.invokeLater(new Runnable() {
    
                public void run() {
                    new MEFIRST().setVisible(true);
                }
            });
        }
       
        // Variables declaration - do not modify
        private javax.swing.JTextField DPW;
        private javax.swing.JLabel DPWL;
        private javax.swing.JTextField HPD;
        private javax.swing.JLabel HPDL;
        private javax.swing.JLabel PPD;
        private javax.swing.JTextField PPH;
        private javax.swing.JLabel PPHL;
        private javax.swing.JLabel PPW;
        private javax.swing.JLabel PPY;
        private javax.swing.JLabel TITLE;
        private javax.swing.JButton jButton1;
        // End of variables declaration
    
        
     
    
    }


    I used NetBeans to make the gui. So when I open it up it just doesnt play the music. Before I put in the try and catch, it gave me an IO error while compiling. The file is in my source folder and I cant understand why it wont work.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,902
    Rep Power
    25

    Default

    it gave me an IO error while compiling.
    What is the "it" that gave the error while compiling?
    You do realize that the compiler (javac) is the program that is executing when the program is being compiled
    and your program when you execute your program.

    Please copy and paste here the full text of the error message.

  3. #3
    seegee is offline Member
    Join Date
    Jul 2011
    Posts
    36
    Rep Power
    0

    Default

    The compiler gave me an error. The error was:
    unreported exception java.io.IOException; must be caught or declared to be thrown

    unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown

    I only got that error when the Try and Catch wasn't there, when the Try and Catch was there it gave me no error but the music wouldnt play when I opened the program.

    Sorry if my terminology is incorrect. I have only been doing this for 3 days.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Well heck, with catch blocks like these, you're flying blind:

    Java Code:
    catch (IOException error) {
      // nothing in here!
    }
    How will you expect to know what went wrong? Don't ignore catches. At least print a stack trace in there.

  5. #5
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default

    Also take the audio code out of that GUI code and try and get it working by itself.
    The rest of that code is simply getting in the way.

    When you have the audio working you can then think about a GUI (though really, don't use the GUI builder).

  6. #6
    seegee is offline Member
    Join Date
    Jul 2011
    Posts
    36
    Rep Power
    0

    Default

    Ok, its still not working when the code is by it self. :/

  7. #7
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,902
    Rep Power
    25

    Default

    Was there error messages? I assume you added: error.printStackTrace() call to the empty catch block.

  8. #8
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    Quote Originally Posted by seegee View Post
    Ok, its still not working when the code is by it self. :/
    There is probably something wrong with the code then. It's hard to say what unless you post it.

    Presumably you intend to hear the sound played continuously, but say what "not working" means: ie, what *does* happen when you run the code. (program exits, runtime exception, strange noises in the speaker etc)

  9. #9
    seegee is offline Member
    Join Date
    Jul 2011
    Posts
    36
    Rep Power
    0

    Default

    Well I did post the code. When I run the program everything works fine but the music. Its like the music code isn't even there. I don't get any errors at all when debugging it and nothing comes out of the speakers. Again, sorry if I sound kind of ignorent I just started Java 4 days ago.

  10. #10
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,902
    Rep Power
    25

    Default

    Did you add the printStackTrace call to the catch block?
    Without that any errors are ignored!!!

  11. #11
    seegee is offline Member
    Join Date
    Jul 2011
    Posts
    36
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    Did you add the printStackTrace call to the catch block?
    Without that any errors are ignored!!!
    Ill try that right now. (If NetBeans will ever open :( )
    Last edited by seegee; 07-20-2011 at 05:46 AM.

  12. #12
    seegee is offline Member
    Join Date
    Jul 2011
    Posts
    36
    Rep Power
    0

    Default

    Ok I tried it and got this error: java.io.IOException: could not create audio stream from input stream
    at sun.audio.AudioStream.<init>(AudioStream.java:65)
    at CJSMoneyMachine.main(CJSMoneyMachine.java:160)

  13. #13
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    Well I did post the code.
    Sorry - I had read the advice that you should separate the business of getting the sound to play from the NB gui code and just assumed you had done that.

    So, what is line 160?

    [Edit]

    Assuming it is "AS= new AudioStream(new FileInputStream("glass_shatter_c.wav"));" then check that the file exists and is readable etc. This may involve writing some code to actually see what file the AudioStream constructor will use.

    Java Code:
    File asFile = new File("glass_shatter_c.wav");
    System.out.println("Using audio file " + f.getCanonicalPath());
    AS= new AudioStream(new FileInputStream("glass_shatter_c.wav"))
    -----

    It would be a good idea to follow Java coding standards and use a descriptive variable starting with a lowercase name: stream or audioStream in place of AS.
    Last edited by pbrockway2; 07-20-2011 at 06:15 AM.

  14. #14
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    Also, is there some reason why you are using the sun.audio.* files rather than, eg, the static Applet method newAudioClip()?

  15. #15
    seegee is offline Member
    Join Date
    Jul 2011
    Posts
    36
    Rep Power
    0

    Default

    Quote Originally Posted by pbrockway2 View Post
    Also, is there some reason why you are using the sun.audio.* files rather than, eg, the static Applet method newAudioClip()?
    I was just watching a tutorial for adding music and I followed it. So i got that code that you gave me and it wont compile right.

    On the System.out.println("Using audio file " + f.getCanonicalPath()); line i get Cannot find symbol, Symbol: variable f

    On the audioStream= new AudioStream(new FileInputStream("300ViolinOrchestra.mp3")); i get Cannot find symbol, Symbol: Variable audioStream

  16. #16
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    f should have been asFile. You have to declare audioStream instead of AS if you want to use it.

    Java Code:
    public static void main(String args[]) {
        AudioPlayer audioPlayer = AudioPlayer.player;
        AudioStream audioStream;
        AudioData audioData;
        ContinuousAudioDataStream loop = null;
            
        try {
            File asFile = new File("glass_shatter_c.wav");
            System.out.println("Using audio file " + asFile.getCanonicalPath());
            audioStream = new AudioStream(new FileInputStream("glass_shatter_c.wav"));
            audioData = audioStream.getData();
            loop = new ContinuousAudioDataStream (audioData);
        } catch (IOException error) {
            error.printStackTrace();
        }
        audioPlayer.start (loop);
            
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MEFIRST().setVisible(true);
            }
        });
    }
    If you are unfamiliar with Java it might be a good idea to work through a basic tutorial like the early sections of Oracle's rather than relying on indifferent code from teh Youtube or whereever. I don't say that to damped your enthusiasm, but because it might prove a more effective approach.
    Tolls likes this.

  17. #17
    seegee is offline Member
    Join Date
    Jul 2011
    Posts
    36
    Rep Power
    0

    Default

    Ok , i tried that code and I get Using audio file /Users/seegee1237/NetBeansProjects/Celcius/300ViolinOrchestra.mp3


    BTW, I switched audio files. Now I am using the Mp3. And I am reading a book on Java. I am currently in the middle of the book. I have kind of learned most of this stuff on my own because the book only focuses on the very basics of java.

  18. #18
    mattxo is offline Member
    Join Date
    Jun 2011
    Posts
    17
    Rep Power
    0

    Default

    here is a little snippet of my code which i know works, I think all you would need to do is edit clip.start(); to clip.loop(x); . x = amount of times to loop. You will also need to edit the chatWindow part to the name of your class.

    AudioInputStream stream = null;
    try {
    File test = new File("chime_up.wav");
    if (test.exists()) {
    stream = AudioSystem.getAudioInputStream(new File("chime_up.wav"));
    AudioFormat format = stream.getFormat();
    stream = AudioSystem.getAudioInputStream(format, stream);

    DataLine.Info info = new DataLine.Info(
    Clip.class, stream.getFormat(), ((int)stream.getFrameLength()*format.getFrameSize( )));
    Clip clip = (Clip) AudioSystem.getLine(info);
    // This method does not return until the audio file is completely loaded
    clip.open(stream);
    // Start playing
    clip.start();

    }

    } catch (IOException ex) {
    Logger.getLogger(chatWindow.class.getName()).log(L evel.SEVERE, null, ex);
    }

    here are my imports
    import javax.sound.sampled.AudioFormat;
    import javax.sound.sampled.AudioInputStream;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.Clip;
    import javax.sound.sampled.DataLine;
    import javax.sound.sampled.LineUnavailableException;
    import javax.sound.sampled.UnsupportedAudioFileException;

  19. #19
    seegee is offline Member
    Join Date
    Jul 2011
    Posts
    36
    Rep Power
    0

    Default

    Quote Originally Posted by mattxo View Post
    here is a little snippet of my code which i know works, I think all you would need to do is edit clip.start(); to clip.loop(x); . x = amount of times to loop. You will also need to edit the chatWindow part to the name of your class.

    AudioInputStream stream = null;
    try {
    File test = new File("chime_up.wav");
    if (test.exists()) {
    stream = AudioSystem.getAudioInputStream(new File("chime_up.wav"));
    AudioFormat format = stream.getFormat();
    stream = AudioSystem.getAudioInputStream(format, stream);

    DataLine.Info info = new DataLine.Info(
    Clip.class, stream.getFormat(), ((int)stream.getFrameLength()*format.getFrameSize( )));
    Clip clip = (Clip) AudioSystem.getLine(info);
    // This method does not return until the audio file is completely loaded
    clip.open(stream);
    // Start playing
    clip.start();

    }

    } catch (IOException ex) {
    Logger.getLogger(chatWindow.class.getName()).log(L evel.SEVERE, null, ex);
    }

    here are my imports
    import javax.sound.sampled.AudioFormat;
    import javax.sound.sampled.AudioInputStream;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.Clip;
    import javax.sound.sampled.DataLine;
    import javax.sound.sampled.LineUnavailableException;
    import javax.sound.sampled.UnsupportedAudioFileException;
    Well I tried your code with my Mp3 and it didnt work. I got an error that said: Exception in thread "main" javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file
    at javax.sound.sampled.AudioSystem.getAudioInputStrea m(AudioSystem.java:1170)
    at CJSMoneyMachine.main(CJSMoneyMachine.java:116)

    I also tried a wav file and got the same error when running

  20. #20
    seegee is offline Member
    Join Date
    Jul 2011
    Posts
    36
    Rep Power
    0

Page 1 of 2 12 LastLast

Similar Threads

  1. No background in FESM
    By NatureFreshMilk in forum New To Java
    Replies: 2
    Last Post: 07-08-2011, 12:17 PM
  2. How to Run a .exe in background???
    By jazz2k8 in forum New To Java
    Replies: 9
    Last Post: 01-21-2011, 12:27 PM
  3. Background in JFrame ( GUI).
    By Twister03 in forum AWT / Swing
    Replies: 2
    Last Post: 03-12-2009, 04:24 AM
  4. Background image
    By leiferouis in forum New To Java
    Replies: 9
    Last Post: 03-08-2009, 06:49 PM
  5. BackGround & ForeGround
    By hungleon88 in forum Advanced Java
    Replies: 3
    Last Post: 08-31-2008, 08:20 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •