❶ 如何用java做一個音樂播放器
首先下載播放mp3的包,比如mp3spi1.9.4.jar。在工程中添加這個包。
播放器演示代碼如下
packagecom.test.audio;
importjava.io.File;
importjava.awt.BorderLayout;
importjava.awt.FileDialog;
importjava.awt.Frame;
importjava.awt.GridLayout;
importjava.awt.Label;
importjava.awt.List;
importjava.awt.Menu;
importjava.awt.MenuBar;
importjava.awt.MenuItem;
importjava.awt.MenuShortcut;
importjava.awt.Panel;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.awt.event.KeyEvent;
importjava.awt.event.MouseAdapter;
importjava.awt.event.MouseEvent;
importjava.awt.event.WindowAdapter;
importjava.awt.event.WindowEvent;
importjavax.sound.sampled.AudioFormat;
importjavax.sound.sampled.AudioInputStream;
importjavax.sound.sampled.AudioSystem;
importjavax.sound.sampled.DataLine;
importjavax.sound.sampled.SourceDataLine;
{
/**
*
*/
=-2605658046194599045L;
booleanisStop=true;//控制播放線程
booleanhasStop=true;//播放線程狀態
液悔Stringfilepath;//播放文件目錄
Stringfilename;//播放文件名稱
;//文件流
AudioFormataudioFormat;//文件格式
SourceDataLinesourceDataLine;//輸出設備
Listlist;//文件列表
Labellabelfilepath;//播放目錄顯示標簽
Labellabelfilename;//播放文件顯示標簽
publicMusicPlayer(){
鬧磨正//設置窗體屬性
setLayout(newBorderLayout());
setTitle("MP3MusicPlayer");
setSize(350,370);
//建立菜單欄
MenuBarmenubar=newMenuBar();
Menumenufile=newMenu("File");
MenuItemmenuopen=newMenuItem("Open",newMenuShortcut(KeyEvent.VK_O));
menufile.add(menuopen);
游宴menufile.addActionListener(newActionListener(){
publicvoidactionPerformed(ActionEvente){
open();
}
});
menubar.add(menufile);
setMenuBar(menubar);
//文件列表
list=newList(10);
list.addMouseListener(newMouseAdapter(){
publicvoidmouseClicked(MouseEvente){
//雙擊時處理
if(e.getClickCount()==2){
//播放選中的文件
filename=list.getSelectedItem();
play();
}
}
});
add(list,"Center");
//信息顯示
Panelpanel=newPanel(newGridLayout(2,1));
labelfilepath=newLabel("Dir:");
labelfilename=newLabel("File:");
panel.add(labelfilepath);
panel.add(labelfilename);
add(panel,"North");
//注冊窗體關閉事件
addWindowListener(newWindowAdapter(){
publicvoidwindowClosing(WindowEvente){
System.exit(0);
}
});
setVisible(true);
}
//打開
privatevoidopen(){
FileDialogdialog=newFileDialog(this,"Open",0);
dialog.setVisible(true);
filepath=dialog.getDirectory();
if(filepath!=null){
labelfilepath.setText("Dir:"+filepath);
//顯示文件列表
list.removeAll();
Filefiledir=newFile(filepath);
File[]filelist=filedir.listFiles();
for(Filefile:filelist){
Stringfilename=file.getName().toLowerCase();
if(filename.endsWith(".mp3")||filename.endsWith(".wav")){
list.add(filename);
}
}
}
}
//播放
privatevoidplay(){
try{
isStop=true;//停止播放線程
//等待播放線程停止
System.out.print("Start:"+filename);
while(!hasStop){
System.out.print(".");
try{
Thread.sleep(10);
}catch(Exceptione){
}
}
System.out.println("");
Filefile=newFile(filepath+filename);
labelfilename.setText("Playing:"+filename);
//取得文件輸入流
audioInputStream=AudioSystem.getAudioInputStream(file);
audioFormat=audioInputStream.getFormat();
//轉換mp3文件編碼
if(audioFormat.getEncoding()!=AudioFormat.Encoding.PCM_SIGNED){
audioFormat=newAudioFormat(AudioFormat.Encoding.PCM_SIGNED,
audioFormat.getSampleRate(),16,audioFormat
.getChannels(),audioFormat.getChannels()*2,
audioFormat.getSampleRate(),false);
audioInputStream=AudioSystem.getAudioInputStream(audioFormat,
audioInputStream);
}
//打開輸出設備
DataLine.InfodataLineInfo=newDataLine.Info(
SourceDataLine.class,audioFormat,
AudioSystem.NOT_SPECIFIED);
sourceDataLine=(SourceDataLine)AudioSystem.getLine(dataLineInfo);
sourceDataLine.open(audioFormat);
sourceDataLine.start();
//創建獨立線程進行播放
isStop=false;
ThreadplayThread=newThread(newPlayThread());
playThread.start();
}catch(Exceptione){
e.printStackTrace();
}
}
classPlayThreadextendsThread{
bytetempBuffer[]=newbyte[320];
publicvoidrun(){
try{
intcnt;
hasStop=false;
//讀取數據到緩存數據
while((cnt=audioInputStream.read(tempBuffer,0,
tempBuffer.length))!=-1){
if(isStop)
break;
if(cnt>0){
//寫入緩存數據
sourceDataLine.write(tempBuffer,0,cnt);
}
}
//Block等待臨時數據被輸出為空
sourceDataLine.drain();
sourceDataLine.close();
hasStop=true;
}catch(Exceptione){
e.printStackTrace();
System.exit(0);
}
}
}
publicstaticvoidmain(Stringargs[]){
newMusicPlayer();
}
}
❷ java如何實現播放mp3
簡單的實例,代碼如下,純粹JMF載入MP3並播放:
import javax.media.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class PlayerMusic implements ControllerListener {// ControllerListener
// 控制事件
private Player player;
private boolean first, loop;
private String path;
private List mp3List;
private int mp3NO = 0;
PlayerMusic(List mp3List) {
this.mp3List = mp3List;
}
public void start() {
try {
player = Manager.createPlayer(new MediaLocator("file://" + mp3List.get(mp3NO)));
} catch (NoPlayerException ex) {
ex.printStackTrace();
System.out.println("不能播放文件");
return;
} catch (IOException ex) {
ex.printStackTrace();
return;
}
if (player == null) {
System.out.println("播放器為空");
return;
}
first = false;
player.addControllerListener(this);
// 提取媒體內容
player.prefetch();
}
public void controllerUpdate(ControllerEvent e) {
// 當媒體播放結束時,循環播放
if (e instanceof EndOfMediaEvent) {
mp3NO++;
if(mp3NO<this.mp3List.size()){
this.start();
}
return;
}
// 當預提取媒體的內容結束
if (e instanceof PrefetchCompleteEvent) {
player.start();
return;
}
// 當實例化後
if (e instanceof RealizeCompleteEvent) {
// pack(); //執行pack()操作
return;
}
}
public static void main(String[] args) {
List mp3List = new ArrayList();
mp3List.add("d://a.mp3");
mp3List.add("d://b.mp3");
mp3List.add("d://c.mp3");
PlayerMusic pm = new PlayerMusic(mp3List);
pm.start();
}
}
❸ java課題設計——視頻播放器怎麼製作
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;import javax.swing.*;
import javax.media.*;public class VideoPlayer extends JFrame implements ActionListener,
ControllerListener {
FileDialog fd;
Player player = null;
String name;
String path;
Component comp, vc;
Image image=new ImageIcon("open.GIF").getImage();
MenuBar mb = new MenuBar();
Menu m1 = new Menu("文件");
Menu m2 = new Menu("幫助");
MenuItem mi1 = new MenuItem("打開", new MenuShortcut(KeyEvent.VK_0));
MenuItem mi2 = new MenuItem("關閉");
MenuItem mi3 = new MenuItem("幫助");
JButton open=new JButton(new ImageIcon("open.GIF")); public VideoPlayer() {
super("視屏播放器");
this.setMenuBar(mb);
mb.add(m1);
mb.add(m2);
m1.add(mi1);
mi1.addActionListener(this);
m1.add(mi2);
mi2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
m2.add(mi3);
mi3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"Java視屏播放器\n2010年6月9日第一版\n製作人: 李攀");
}
});
this.setLayout(new BorderLayout());
this.setSize(800, 650);
this.setVisible(true);
this.setBackground(Color.BLACK);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
} public static void main(String[] args) {
new VideoPlayer();
} public void actionPerformed(ActionEvent e) {
if (e.getSource() == mi1) {
open();
}
} public void open() {
fd = new FileDialog(this, "打開媒體文件", FileDialog.LOAD);
fd.setVisible(true);
path = fd.getDirectory();
name = fd.getFile();
if (!path.equals("") && path != null) {
try {
if (player != null)
player.close();
player = Manager.createPlayer(new MediaLocator("file:" + path
+ name));
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "獲取播放器失敗!");
}
player.addControllerListener(this);
player.prefetch();
player.start();
}
} public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, 800, 650);
g.setColor(Color.GREEN);
g.setFont(new Font("宋體",Font.BOLD,30));
g.drawString("歡迎使用",340,150);
g.drawImage(image,330,285,image.getWidth(this),image.getHeight(this),this);
}
public void update(Graphics g){
paint(g);
} public synchronized void controllerUpdate(ControllerEvent e) {
if (e instanceof RealizeCompleteEvent) {
if ((comp = player.getControlPanelComponent()) != null) {
vc = player.getVisualComponent();
if (vc != null)
add(vc);
add("South", comp);
comp.setBackground(Color.green);
}
validate();
}
if (e instanceof ControllerClosedEvent) {
if (vc != null) {
remove(vc);
vc = null;
}
if (comp != null) {
remove(comp);
comp = null;
}
return;
}
if (e instanceof EndOfMediaEvent) {
player.setMediaTime(new Time(0));
player.start();
return;
}
}
}
java的視屏播放要用到JMF(java media framework),你自己到網上去下一個嘛,而且那玩意支持的格式少,mpg,mpeg,sun的官方網站說支持AVI但是我試過了好像不行,至於rmvb那些好像不行,要裝解碼器。JMF在安裝的時候要安裝對哦,路徑要選擇對,不然不行,具體下載地址和安裝方法可以網路一下,到處都是
❹ 怎麼用java實現一個簡單的播放器
用java實現播放器 主要用到java里的媒體框架,即JMF, JMF實際上是Java的一個類包。JMF 2.1.1技術提供了先進的媒體處理能力,從而擴展了Java平台的功能。這些功能包括:媒體捕獲、壓縮、流轉、回放,以及對各種主要媒體形式和編碼的支 持,如M-JPEG、H.263、MP3、RTP/RTSP (實時傳送協議和實時流轉協議)、Macromedias Flash、IBM的HotMedia和Beatniks的Rich Media Format (RMF)等。JMF 2.1.1還支持廣受歡迎的媒體類型,如Quicktime、Microsofts AVI和MPEG-1等。此外,JMF 2.1.1軟體中包括了一個開放的媒體架構,可使開發人員靈活採用各種媒體回放、捕獲組件,或採用他們自己的定製的內插組件。 我當初也做過類似的東西(本科實習時),給你個具體教程鏈接吧: http://hi..com/samxx8/blog/item/90532ba4d13fcdf69052ee5c.html
❺ 如何用Java來編寫一個音樂播放器
首先要在環境電腦中安裝下JMF環境,才能引入javax.sound.sampled.*這個包,一跡和下是用過的代碼
package TheMusic;
import java.io.*;
import javax.sound.sampled.*;
public class Music {
public static void main(String[] args) {
// TODO Auto-generated method stub
//修改你的音樂文仿州擾件路徑就OK了
AePlayWave apw=new AePlayWave("突然備旦好想你.wav");
apw.start();
}
}
在程序中實例化這個類,啟動線程,實例化的時候參照Test修改路徑就OK播放聲音的類
Java代碼
public class AePlayWave extends Thread {
private String filename;
public AePlayWave(String wavfile) {
filename = wavfile;
}
public void run() {
File soundFile = new File(filename);
AudioInputStream audioInputStream = null;
try {
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
} catch (Exception e1) {
e1.printStackTrace();
return;
}
AudioFormat format = audioInputStream.getFormat();
SourceDataLine auline = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
try {
auline = (SourceDataLine) AudioSystem.getLine(info);
auline.open(format);
} catch (Exception e) {
e.printStackTrace();
return;
}
auline.start();
int nBytesRead = 0;
byte[] abData = new byte[512];
try {
while (nBytesRead != -1) {
nBytesRead = audioInputStream.read(abData, 0, abData.length);
if (nBytesRead >= 0)
auline.write(abData, 0, nBytesRead);
}
} catch (IOException e) {
e.printStackTrace();
return;
} finally {
auline.drain();
auline.close();
}
}
}