Question about play mp3 file in java

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 3156 Views - Last Post: 17 December 2011 - 03:02 AM Rate Topic: -----

#1 pro_learner  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 30
  • Joined: 25-August 10

Question about play mp3 file in java

Posted 15 December 2011 - 09:13 PM

Guys,i have developed a Java Application.I have already connected it with MySql DB & it's working properly.In DB there is a table calls Music and in that table contains a field calls Song _Path.It includes the path of the song in my computer.In java application there is a "Play" button.After selecting the relevant song(There is seperate button for that and it's working),the song should be played.I search about this in this forum and i got this option and i downloaded that file.
My link
I don't know how to use this in my application.Please help me to solve this.

Is This A Good Question/Topic? 0
  • +

Replies To: Question about play mp3 file in java

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Question about play mp3 file in java

Posted 15 December 2011 - 10:37 PM

Asked so many times

http://www.devx.com/tips/Tip/38856
Was This Post Helpful? 0
  • +
  • -

#3 pro_learner  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 30
  • Joined: 25-August 10

Re: Question about play mp3 file in java

Posted 15 December 2011 - 10:47 PM

Please tell me how to use this code?I don't have an idea...
Was This Post Helpful? 0
  • +
  • -

#4 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Question about play mp3 file in java

Posted 15 December 2011 - 10:57 PM

Java standard API does not support .MP3
Until few years ago you had to rely on third party software the JMF (Java Media Framework) librairy to play with .MP3 is now available
Google java mp3
for more examples
Was This Post Helpful? 1
  • +
  • -

#5 pro_learner  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 30
  • Joined: 25-August 10

Re: Question about play mp3 file in java

Posted 15 December 2011 - 11:08 PM

Thanks.....i'll do that....

I google it...I got first search result as....http://www.javazoom.net/javalayer/sources.html
I have already downloaded it.My question is i don't know how to use that...
Was This Post Helpful? 0
  • +
  • -

#6 pro_learner  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 30
  • Joined: 25-August 10

Re: Question about play mp3 file in java

Posted 16 December 2011 - 03:05 AM

I do not know,how to add this library to my project.....
Was This Post Helpful? 0
  • +
  • -

#7 pro_learner  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 30
  • Joined: 25-August 10

Re: Question about play mp3 file in java

Posted 16 December 2011 - 03:16 AM

In the read me file of the jLayer says,"Before running JLayer you must set PATH and CLASSPATH for JAVA and you must add jl1.0.1.jar to the CLASSPATH."...What's that?
Was This Post Helpful? 0
  • +
  • -

#8 pro_learner  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 30
  • Joined: 25-August 10

Re: Question about play mp3 file in java

Posted 16 December 2011 - 06:34 AM

Thanks all of you for your help.Finally i could solve my issue.Cheers!!!now it's working..:):)
Was This Post Helpful? 0
  • +
  • -

#9 pro_learner  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 30
  • Joined: 25-August 10

Re: Question about play mp3 file in java

Posted 16 December 2011 - 09:17 PM

Thank guys.The problem was,i have added the .jar file correctly.But i have imported a wrong java library to the project.Because when i did a google search i got a tutorial about jLayer.In that tutorial they have imported "javax.media".So i also tried to import that.But it didn't worked.Then i tried the "import javazoom.jl.player.Player" one.Then it worked.hmm......but there is a small problem.It plays the mp3 file properly.Is there any option to stop or pause the file.If you guys can give me a solution to that small problem i'm admiring that...Thanks..
This is my Code

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * musicgui.java
 *
 * Created on Dec 12, 2011, 11:26:11 AM
 */
package GUI;
import java.sql.*;
import javazoom.jl.player.Player;
import java.io.FileInputStream;
/**
 *
 * @author pro_learner
 */
public class musicgui extends javax.swing.JFrame {
     
    /** Creates new form musicgui */
    public musicgui() {
        initComponents();
        setTitle("Music Explorer Developed By Buddhi Eashwarage");
    }

    /** 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() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel1.setText("Song ID");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel2.setText("Song Name");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel3.setText("Artist");

        jButton1.setFont(new java.awt.Font("Tahoma", 1, 11));
        jButton1.setText("View");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setFont(new java.awt.Font("Tahoma", 1, 11));
        jButton2.setText("Exit");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setFont(new java.awt.Font("Tahoma", 1, 11));
        jButton3.setText("Clear");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jButton4.setText("Play Song");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jButton5.setText("Stop Playing");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel4.setText("Song Path");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE, 243, Short.MAX_VALUE)
                        .addGap(577, 577, 577))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(577, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addGap(40, 40, 40)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jTextField2)
                                    .addComponent(jTextField3)
                                    .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE))
                                .addGap(18, 18, 18)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jButton1)
                                    .addComponent(jButton3)))
                            .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 406, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap(311, Short.MAX_VALUE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton1)))
                .addGap(28, 28, 28)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton3))
                .addGap(35, 35, 35)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 41, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(34, 34, 34)
                .addComponent(jButton4)
                .addGap(26, 26, 26)
                .addComponent(jButton5)
                .addGap(80, 80, 80)
                .addComponent(jButton2)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
           String DataSourceName="musicdbconnection";
           String DBUrl="jdbc:odbc:"+DataSourceName;
           
           try{
           Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
           Connection con=DriverManager.getConnection(DBUrl,"","");
           Statement s=con.createStatement();
           
           //s.execute("insert into music_data(Song_Name,Artist_Name,Song_Path)values('Mal Pita Mal','Amal Perera','aaaaaaa')");
           int n=Integer.parseInt(jTextField1.getText());
           s.execute("select * from music_data where Song_Num="+n+";");
           
           ResultSet rs=s.getResultSet();
           
           if(rs!=null)
           {
           while(rs.next())
           {
               //System.out.println("Song Number:"+rs.getInt(1)+" "+"Song Name:"+rs.getString(2)+" "+"Artist Name:"+rs.getString(3));
               jTextField1.setText(""+rs.getInt(1));
               jTextField2.setText(rs.getString(2));
               jTextField3.setText(rs.getString(3));
               jTextField4.setText(rs.getString(4));
               
           }
           }
           
           s.close();
           con.close();
           }catch(Exception e){
           System.out.println("Music"+e);
           }
    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        System.exit(0);
    }                                        

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        jTextField1.setText("");
        jTextField2.setText("");
        jTextField3.setText("");
    }                                        

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        try  
        {  
            String n=jTextField4.getText();
            FileInputStream fis=new FileInputStream(n);  
            Player playMp3=new Player(fis);  
              
            playMp3.play();  
        }  
        catch(Exception e)  
        {  
            System.out.println(e);  
        }  
    }                                        

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(musicgui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(musicgui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(musicgui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(musicgui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new musicgui().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    // End of variables declaration                   
}

Was This Post Helpful? 0
  • +
  • -

#10 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Question about play mp3 file in java

Posted 16 December 2011 - 09:27 PM

Stay away from GUI generator and write your own GUI.
Nobody will waste his time trying to decipher the horrible, almost unredeable by human beings, code produced by a GUI generator.
Was This Post Helpful? 0
  • +
  • -

#11 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Question about play mp3 file in java

Posted 16 December 2011 - 09:32 PM

I presume that Player is coming from javazoom.jl

if they have a play() method sure that they have a stop() end evene a pause() methods
Just look at the javadoc that comes with it
Was This Post Helpful? 0
  • +
  • -

#12 pro_learner  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 30
  • Joined: 25-August 10

Re: Question about play mp3 file in java

Posted 16 December 2011 - 09:49 PM

Sorry for that...still i don't know work with swing package manually.That's why i was used auto generated code.Again sorry for that.Yes i can understand your solution.If you can please check line number 236 to 248.That's the code for play music that i have used.I have wrote that code inside the "Play Button".So when i write a code to stop button,how can do that?Because i have declare the inputstream inside the Play Button...
Was This Post Helpful? 0
  • +
  • -

#13 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Question about play mp3 file in java

Posted 16 December 2011 - 09:57 PM

I don't know the third party package you download but as I've said sure that they have a stop() method. But one thing for sure

      try {
           Player playMp3=new Player(fis);  // you declare playMp3 here
            playMp3.play();  

      }   // <--- you won't be able to access it after here


it has been declared inside the try{} and could not be access from somewhere else
you will have to declare Player playMp3 in your instance variables
Was This Post Helpful? 0
  • +
  • -

#14 pro_learner  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 30
  • Joined: 25-August 10

Re: Question about play mp3 file in java

Posted 16 December 2011 - 10:05 PM

hmm...yes.I'll try to do that.Thanks
Was This Post Helpful? 0
  • +
  • -

#15 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1155
  • View blog
  • Posts: 2,533
  • Joined: 05-May 05

Re: Question about play mp3 file in java

Posted 16 December 2011 - 10:31 PM

Here's a little something I threw together. I've been using JavaZoom as well. To stop the song you need to call close() on the SoureceDataLine. If your in a loop relaying bytes from the AudioInputStream to the SourceDataLine, you can simply exit the loop, which is what I do here. I haven't looked into pausing and all that, as I haven't gotten to that requirement in my application yet. AudioPlayer.java has most of what's probably important to you.

To run it, you need to download MP3SPI 1.9.5 from JavaZoom's site, and throw the 3 jars into the directory with the class files. 2 of the jars are in the lib directory.

Run cmd:

javac *.java
java -classpath .:jl1.0.1.jar:mp3spi1.9.5.jar:tritonus_share.jar MP3Player



If you're on a Linux box, use semi-colons instead of colons for the classpath.

MP3Player.java:

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.UIManager;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class MP3Player {

    private String laf = "Nimbus";
    private JFrame frmMpPlayer;
    private JTextField textField;
    private AudioPlayer player;
    private String songPath;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MP3Player window = new MP3Player();
                    window.frmMpPlayer.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public MP3Player() {
        player = new AudioPlayer();
        setLookAndFeel(laf);
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frmMpPlayer = new JFrame();
        frmMpPlayer.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                player.stopSong();
            }
        });
        frmMpPlayer.setTitle("Mp3 Player");
        frmMpPlayer.setBounds(100, 100, 450, 100);
        frmMpPlayer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmMpPlayer.getContentPane().setLayout(
                new BoxLayout(frmMpPlayer.getContentPane(), BoxLayout.Y_AXIS));

        JPanel panel = new JPanel();
        panel.setMaximumSize(new Dimension(32767, 30));
        panel.setPreferredSize(new Dimension(10, 30));
        frmMpPlayer.getContentPane().add(panel);
        panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));

        JButton btnBrowse = new JButton("Browse");
        btnBrowse.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JFileChooser fc = new JFileChooser();
                int returnVal = fc.showOpenDialog(null);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = fc.getSelectedFile();
                    songPath = file.getPath();
                    textField.setText(songPath);
                }
            }
        });
        panel.add(btnBrowse);

        JSeparator separator = new JSeparator();
        separator.setPreferredSize(new Dimension(5, 2));
        panel.add(separator);

        textField = new JTextField();
        panel.add(textField);
        textField.setColumns(10);

        JPanel panel_1 = new JPanel();
        panel_1.setMaximumSize(new Dimension(32767, 30));
        panel_1.setMinimumSize(new Dimension(32767, 30));
        panel_1.setPreferredSize(new Dimension(32767, 30));
        frmMpPlayer.getContentPane().add(panel_1);
        panel_1.setLayout(new BoxLayout(panel_1, BoxLayout.X_AXIS));

        JButton btnPlay = new JButton("Play");
        btnPlay.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new Thread(new Runnable() {
                    public void run() {
                        player.playSong(songPath);
                    }
                }).start();
            }
        });
        panel_1.add(btnPlay);

        JButton btnStop = new JButton("Stop");
        btnStop.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                player.stopSong();
            }
        });
        panel_1.add(btnStop);
    }

    private void setLookAndFeel(String laf) {
        try {
            for (UIManager.LookAndFeelInfo info : UIManager
                    .getInstalledLookAndFeels()) {
                if (laf.equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}



AudioPlayer.java

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

public class AudioPlayer {

    private SourceDataLine line;
    private boolean isPlaying;

    public void playSong(String filename) {
        try {
            File file = new File(filename);
            AudioInputStream in = AudioSystem.getAudioInputStream(file);
            AudioInputStream din = null;
            AudioFormat baseFormat = in.getFormat();
            AudioFormat decodedFormat = new AudioFormat(
                    AudioFormat.Encoding.PCM_SIGNED,
                    baseFormat.getSampleRate(), 16, baseFormat.getChannels(),
                    baseFormat.getChannels() * 2, baseFormat.getSampleRate(),
                    false);
            din = AudioSystem.getAudioInputStream(decodedFormat, in);
            // Play now.
            rawplay(decodedFormat, din);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stopSong() {
        isPlaying = false;
    }

    private void rawplay(AudioFormat targetFormat, AudioInputStream din)
            throws IOException, LineUnavailableException {
        byte[] data = new byte[4096];
        line = getLine(targetFormat);
        if (line != null) {
            isPlaying = true;
            // Start
            line.start();
            int nBytesRead = 0, nBytesWritten = 0;
            while (nBytesRead != -1 && isPlaying) {
                nBytesRead = din.read(data, 0, data.length);
                if (nBytesRead != -1)
                    nBytesWritten = line.write(data, 0, nBytesRead);
            }
            // Stop
            line.drain();
            line.stop();
            line.close();
            din.close();
        }
    }

    private SourceDataLine getLine(AudioFormat audioFormat)
            throws LineUnavailableException {
        SourceDataLine res = null;
        DataLine.Info info = new DataLine.Info(SourceDataLine.class,
                audioFormat);
        res = (SourceDataLine) AudioSystem.getLine(info);
        res.open(audioFormat);
        return res;
    }

    public static void main(String[] args) {
        String path = "";
        new AudioPlayer().playSong(path);
    }
}


This post has been edited by blackcompe: 16 December 2011 - 10:33 PM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2