import java.io.FileInputStream;
import java.io.IOException;
import javax.sound.sampled.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.Thread;
import Limit.*;
public class Jmp3 extends JFrame implements ActionListener
{
JButton open,close;
JFileChooser jfc;
Jmp3()
{
super("Java MP3 Player");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
setSize(400,300);
setVisible(true);
close = new JButton("Close");
open = new JButton("Open");
close.addActionListener(this);
open.addActionListener(this);
this.add(close);
this.add(open);
jfc = new JFileChooser();
jfc.addChoosableFileFilter(new ImageFilter());
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getActionCommand() == "Close")
System.exit(0);
if(ae.getActionCommand() == "Open")
play();
}
public void play()
{
if(jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
{
AudioInputStream din = null;
try
{
FileInputStream file = new FileInputStream(jfc.getSelectedFile());
AudioInputStream in = AudioSystem.getAudioInputStream(file);
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);
DataLine.Info info = new DataLine.Info(SourceDataLine.class, decodedFormat);
SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
if(line != null)
{
line.open(decodedFormat);
byte[] data = new byte[4096];
// Start
line.start();
int nBytesRead;
while ((nBytesRead = din.read(data, 0, data.length)) != -1)
{
line.write(data, 0, nBytesRead);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if(din != null)
{
try
{
din.close();
}
catch(IOException e)
{
// Nothing here
}
}
}
}
}
public static void main(String[] args)
{
new Jmp3();
}
}
package Limit;
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.*;
public class ImageFilter extends FileFilter
{
public boolean accept(File f)
{
String extension = Utils.getExtension(f);
if (extension != null)
{
if (extension.equals(Utils.bpt))
{
return true;
}
else
{
return false;
}
}
return false;
}
public String getDescription()
{
return "MP3 Audio File (.mp3)";
}
}
class Utils
{
public final static String bpt = "mp3";
public static String getExtension(File f)
{
String ext = null;
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1)
ext = s.substring(i+1).toLowerCase();
return ext;
}
}
@prasath_amd,thanx for the code.but i prefer to do it myself.
how do i add codec support?
I gave it only to give u some basic idea tats all.......