【仅能播放wav格式的文件】
package music; import javax.swing.*;
import java.io.*;
import javax.sound.sampled.*;
import javax.sound.midi.*;
import java.awt.*;
import java.awt.event.*;
import javax.sound.sampled.AudioFormat.Encoding;
import java.util.*;
//高效设计:如果要设计一个要在其它类作为线程的类,最好把此类设计为Runnable型
//不要在此类中调用线程,最好把此类作为一个Runnable接口使用
public class Mp3Ecoding implements Runnable
{
String filename;
AudioInputStream stream;
SourceDataLine playLine;
AudioFormat baseFormat;
long currentByte = 0;
boolean isPause;
int numThread = 0;
int numBytesRead = -1;
int bufferSize;
private FileInputStream in;
public Mp3Ecoding()
{ //currentByte = bufferSize;
}
private void getFormat(String filename)
{ try
{
//in = new FileInputStream(new File(filename));
//AudioFileFormat af = mt.getAudioFileFormat(in);
stream = AudioSystem.getAudioInputStream(new File(filename));
}
catch(Exception e)
{
e.printStackTrace();
}
baseFormat = stream.getFormat();
int firstExtendnameIndex = filename.lastIndexOf(".");
String extendStr = filename.substring(firstExtendnameIndex+1);
if(!extendStr.equalsIgnoreCase("wav"))
{
System.out.println(String.valueOf(extendStr.equalsIgnoreCase("wav")));
baseFormat = decodingMusic(baseFormat);
} }
private AudioFormat decodingMusic(AudioFormat format)
{
AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
format.getSampleRate(),
format.getSampleSizeInBits(),
format.getChannels(),
format.getFrameSize(),
format.getFrameRate(),
format.isBigEndian());
return decodedFormat;
}
private SourceDataLine getLine(AudioFormat f)
{
RandomAccessFile source = null;
try{
source = new RandomAccessFile(filename,"r");
}catch(Exception e){}
SourceDataLine line = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class,f);
bufferSize = baseFormat.getFrameSize() *
Math.round(baseFormat.getSampleRate() / 10);
byte[] buffer = new byte[bufferSize];
try
{
line = (SourceDataLine)AudioSystem.getLine(info);
line.open(f, bufferSize);
}
catch (LineUnavailableException ex)
{
ex.printStackTrace();
}
line.start(); // copy data to the line
try { //do{
if((numBytesRead == -1)&&(MusicFrame.getIsPlay() == true)) {
currentByte = buffer.length;
numBytesRead = 0;
}
source.seek(currentByte); while ((numBytesRead != -1)&&(MusicFrame.getIsPause()!=true)) {
numBytesRead = source.read(buffer, 0, buffer.length);
currentByte += numBytesRead;
if (numBytesRead != -1) {
line.write(buffer, 0, numBytesRead);
}
}
if(MusicFrame.getIsStop() == true) currentByte = buffer.length;
//}while((MusicFrame.getIsCycle() == true)&&(numBytesRead == -1));
}
catch (Exception ex) {
ex.printStackTrace();
} return line;
} public void run()
{ play();
}
public synchronized void play()
{
setFilename(filename);
getFormat(filename); playLine = getLine(baseFormat);
//playLine.drain();//write会自动调用drain方法
if((MusicFrame.getIsCycle() == true)&&(MusicFrame.getIsPlay() == true))
{
Random f = new Random();
int index = f.nextInt(MusicFrame.getNameList().size()); filename = (String)MusicFrame.getNameList().getElementAt(index); play();
}
playLine.close();
//numThread = 0;
}
public void setFilename(String name)
{
if(name == null)
{
name = MusicFrame.getFilename();
}
filename = name;
} }
package music;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.event.*;
public class MusicFrame extends JFrame
{
private JButton playButn = new JButton();
private JButton stopButn = new JButton();
private JButton pauseButn = new JButton();
private JButton upButn = new JButton();
private JButton backButn = new JButton();
private static DefaultListModel nameList = new DefaultListModel();
private JList filenamesList = new JList(nameList);
private JPanel butnPanel = new JPanel();
private JMenuBar musicBar = new JMenuBar();
private JMenu file = new JMenu("file");
private JMenuItem open = new JMenuItem("open");
private JFileChooser chooser = new JFileChooser("E:\1");
private static String filename = null;
private JScrollPane scroll = new JScrollPane(filenamesList);
private Mp3Ecoding mp = new Mp3Ecoding();
private static boolean isStop = false;
private static boolean isPause = false;
private static boolean isPlay = false;
private static boolean isCycle = false;
public MusicFrame()
{
super("音乐播放器");
nameList.addElement("3.wav");
filenamesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
filenamesList.setVisibleRowCount(10);
Dimension d = new Dimension(500,300);
this.filenamesList.setPreferredSize(d);
ULinit();
} private void addButnIconText(JButton button,String text,ImageIcon icon)
{
button.setText(text);
button.setIcon(icon);
button.setIconTextGap(5);
butnPanel.add(button);
}
private void ULinit()
{
addButnIconText(playButn,"play",new ImageIcon("play.png"));
playButn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{ isPlay = true;
isPause = false;
isStop = false;
new Thread(mp).start();
}
}); addButnIconText(stopButn,"stop",new ImageIcon("stop.png"));
stopButn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
isStop = true;
isPause = true;
isPlay = false;
}
});
addButnIconText(pauseButn,"pause",new ImageIcon("pause.png"));
pauseButn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
isPlay = false;
isPause = true;
isStop = false;
}
});
addButnIconText(upButn,"up",new ImageIcon("up.png"));
upButn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{ }
});
addButnIconText(backButn,"CyclePlay",new ImageIcon("back.png"));
backButn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
isCycle = true;
isStop = false;
isPause = false;
isPlay = true; /*if(mp == null)
{
mp = new Mp3Ecoding();
}*/ //new Thread(mp).start();
}
});
open.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
openFile();
}
});
filenamesList.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent lse)
{
if (!lse.getValueIsAdjusting())
{
isStop = true;
isPause = true;
filename = (String)filenamesList.getSelectedValue();
/*if(mp == null)
{
mp = new Mp3Ecoding();
}*/ }
}
});
file.add(open);
musicBar.add(file);
this.setJMenuBar(musicBar);
this.getContentPane().add(butnPanel,"South");
this.getContentPane().add(scroll,"Center");
}
private void openFile()
{
try
{
int interval = 0;
interval = chooser.showOpenDialog(this);
if(interval == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
nameList.addElement(new String(file.getName()));
}
}catch(HeadlessException e)
{
e.printStackTrace();
}catch(Exception e)
{
e.printStackTrace();
} }
public static boolean getIsPause()
{
return isPause;
}
public static boolean getIsStop()
{
return isStop;
}
public static boolean getIsPlay()
{
return isPlay;
}
public static DefaultListModel getNameList()
{
return nameList;
}
public static boolean getIsCycle()
{
return isCycle;
}
public static String getFilename()
{
return filename;
}
public static void main(String[] args)
{
MusicFrame musicf = new MusicFrame();
musicf.setLocation(250,250);
musicf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
musicf.pack();
musicf.setVisible(true); }
}
package music; import javax.swing.*;
import java.io.*;
import javax.sound.sampled.*;
import javax.sound.midi.*;
import java.awt.*;
import java.awt.event.*;
import javax.sound.sampled.AudioFormat.Encoding;
import java.util.*;
//高效设计:如果要设计一个要在其它类作为线程的类,最好把此类设计为Runnable型
//不要在此类中调用线程,最好把此类作为一个Runnable接口使用
public class Mp3Ecoding implements Runnable
{
String filename;
AudioInputStream stream;
SourceDataLine playLine;
AudioFormat baseFormat;
long currentByte = 0;
boolean isPause;
int numThread = 0;
int numBytesRead = -1;
int bufferSize;
private FileInputStream in;
public Mp3Ecoding()
{ //currentByte = bufferSize;
}
private void getFormat(String filename)
{ try
{
//in = new FileInputStream(new File(filename));
//AudioFileFormat af = mt.getAudioFileFormat(in);
stream = AudioSystem.getAudioInputStream(new File(filename));
}
catch(Exception e)
{
e.printStackTrace();
}
baseFormat = stream.getFormat();
int firstExtendnameIndex = filename.lastIndexOf(".");
String extendStr = filename.substring(firstExtendnameIndex+1);
if(!extendStr.equalsIgnoreCase("wav"))
{
System.out.println(String.valueOf(extendStr.equalsIgnoreCase("wav")));
baseFormat = decodingMusic(baseFormat);
} }
private AudioFormat decodingMusic(AudioFormat format)
{
AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
format.getSampleRate(),
format.getSampleSizeInBits(),
format.getChannels(),
format.getFrameSize(),
format.getFrameRate(),
format.isBigEndian());
return decodedFormat;
}
private SourceDataLine getLine(AudioFormat f)
{
RandomAccessFile source = null;
try{
source = new RandomAccessFile(filename,"r");
}catch(Exception e){}
SourceDataLine line = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class,f);
bufferSize = baseFormat.getFrameSize() *
Math.round(baseFormat.getSampleRate() / 10);
byte[] buffer = new byte[bufferSize];
try
{
line = (SourceDataLine)AudioSystem.getLine(info);
line.open(f, bufferSize);
}
catch (LineUnavailableException ex)
{
ex.printStackTrace();
}
line.start(); // copy data to the line
try { //do{
if((numBytesRead == -1)&&(MusicFrame.getIsPlay() == true)) {
currentByte = buffer.length;
numBytesRead = 0;
}
source.seek(currentByte); while ((numBytesRead != -1)&&(MusicFrame.getIsPause()!=true)) {
numBytesRead = source.read(buffer, 0, buffer.length);
currentByte += numBytesRead;
if (numBytesRead != -1) {
line.write(buffer, 0, numBytesRead);
}
}
if(MusicFrame.getIsStop() == true) currentByte = buffer.length;
//}while((MusicFrame.getIsCycle() == true)&&(numBytesRead == -1));
}
catch (Exception ex) {
ex.printStackTrace();
} return line;
} public void run()
{ play();
}
public synchronized void play()
{
setFilename(filename);
getFormat(filename); playLine = getLine(baseFormat);
//playLine.drain();//write会自动调用drain方法
if((MusicFrame.getIsCycle() == true)&&(MusicFrame.getIsPlay() == true))
{
Random f = new Random();
int index = f.nextInt(MusicFrame.getNameList().size()); filename = (String)MusicFrame.getNameList().getElementAt(index); play();
}
playLine.close();
//numThread = 0;
}
public void setFilename(String name)
{
if(name == null)
{
name = MusicFrame.getFilename();
}
filename = name;
} }
package music;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.event.*;
public class MusicFrame extends JFrame
{
private JButton playButn = new JButton();
private JButton stopButn = new JButton();
private JButton pauseButn = new JButton();
private JButton upButn = new JButton();
private JButton backButn = new JButton();
private static DefaultListModel nameList = new DefaultListModel();
private JList filenamesList = new JList(nameList);
private JPanel butnPanel = new JPanel();
private JMenuBar musicBar = new JMenuBar();
private JMenu file = new JMenu("file");
private JMenuItem open = new JMenuItem("open");
private JFileChooser chooser = new JFileChooser("E:\1");
private static String filename = null;
private JScrollPane scroll = new JScrollPane(filenamesList);
private Mp3Ecoding mp = new Mp3Ecoding();
private static boolean isStop = false;
private static boolean isPause = false;
private static boolean isPlay = false;
private static boolean isCycle = false;
public MusicFrame()
{
super("音乐播放器");
nameList.addElement("3.wav");
filenamesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
filenamesList.setVisibleRowCount(10);
Dimension d = new Dimension(500,300);
this.filenamesList.setPreferredSize(d);
ULinit();
} private void addButnIconText(JButton button,String text,ImageIcon icon)
{
button.setText(text);
button.setIcon(icon);
button.setIconTextGap(5);
butnPanel.add(button);
}
private void ULinit()
{
addButnIconText(playButn,"play",new ImageIcon("play.png"));
playButn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{ isPlay = true;
isPause = false;
isStop = false;
new Thread(mp).start();
}
}); addButnIconText(stopButn,"stop",new ImageIcon("stop.png"));
stopButn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
isStop = true;
isPause = true;
isPlay = false;
}
});
addButnIconText(pauseButn,"pause",new ImageIcon("pause.png"));
pauseButn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
isPlay = false;
isPause = true;
isStop = false;
}
});
addButnIconText(upButn,"up",new ImageIcon("up.png"));
upButn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{ }
});
addButnIconText(backButn,"CyclePlay",new ImageIcon("back.png"));
backButn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
isCycle = true;
isStop = false;
isPause = false;
isPlay = true; /*if(mp == null)
{
mp = new Mp3Ecoding();
}*/ //new Thread(mp).start();
}
});
open.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
openFile();
}
});
filenamesList.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent lse)
{
if (!lse.getValueIsAdjusting())
{
isStop = true;
isPause = true;
filename = (String)filenamesList.getSelectedValue();
/*if(mp == null)
{
mp = new Mp3Ecoding();
}*/ }
}
});
file.add(open);
musicBar.add(file);
this.setJMenuBar(musicBar);
this.getContentPane().add(butnPanel,"South");
this.getContentPane().add(scroll,"Center");
}
private void openFile()
{
try
{
int interval = 0;
interval = chooser.showOpenDialog(this);
if(interval == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
nameList.addElement(new String(file.getName()));
}
}catch(HeadlessException e)
{
e.printStackTrace();
}catch(Exception e)
{
e.printStackTrace();
} }
public static boolean getIsPause()
{
return isPause;
}
public static boolean getIsStop()
{
return isStop;
}
public static boolean getIsPlay()
{
return isPlay;
}
public static DefaultListModel getNameList()
{
return nameList;
}
public static boolean getIsCycle()
{
return isCycle;
}
public static String getFilename()
{
return filename;
}
public static void main(String[] args)
{
MusicFrame musicf = new MusicFrame();
musicf.setLocation(250,250);
musicf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
musicf.pack();
musicf.setVisible(true); }
}
javac -d . *.java
java wd.MusicFrame
javac Mp3Ecoding.java
javac MusicFrame.java
java MusicFrame
我这边没问题