當前位置:首頁 » 操作系統 » java播放器源碼

java播放器源碼

發布時間: 2023-03-07 02:39:10

Ⅰ 如何用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編寫的視頻播放器程序

不全~代碼發不了了~,剩下的是播放器的關閉以及播放格式的支持與否,不麻煩的自己寫吧
MediaPlayer.java
----------------------------------------------------------------------------
//程序主文件
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.media.*;
import java.io.*;
import java.util.*;//為了導入Vector
//import com.sun.java.swing.plaf.windows.*;

public class MediaPlayer extends JFrame implements ActionListener,Runnable
{
private JMenuBar bar;//菜單條
private JMenu fileMenu,choiceMenu,aboutMenu;
private JMenuItem openItem,openDirItem,closeItem,about,infor;
private JCheckBoxMenuItem onTop;
private boolean top=false,loop;//設定窗口是否在最前面
private Player player;//Play是個實現Controller的介面
private File file,listFile;//利用File類結合JFileChooser進行文件打開操作,後則與list.ini有關
private Container c;
//private UIManager.LookAndFeelInfo[] look;
private String title,listIniAddress;//標題
private FileDialog fd;
private JPanel panel,panelSouth;
private Icon icon; //開始進入的時候要顯示的圖標,它為抽象類,不能自己創建
private JLabel label,listB;//用來顯示圖標

private JList list;//播放清單
private JScrollPane scroll;//使播放清單具有滾動功能
private ListValues listWriteFile;//用於向文件中讀取對象
private ObjectInputStream input;//對象輸入流
private ObjectOutputStream output;//對象輸出流

private JPopupMenu popupMenu;//滑鼠右鍵彈出菜單
private JMenuItem del,delAll,reName; //彈出菜單顯示的菜單項,包括刪除,全部刪除和重命名

private Vector fileName,dirName,numList;
private String files,dir;
private int index;//曲目指針
private Properties prop;//獲得系統屬性
private int indexForDel;//標志要刪除的列表項目的索引
private ButtonGroup buttonGroup;//控制按鈕組
private JRadioButtonMenuItem[] buttonValues;
private String[] content={"隨機播放","順序播放","單曲循環"};

private DialogDemo dialog1;
//private JDialogTest dialog2;//用於顯示播放清單

MediaPlayer()//構造函數
{
super("java音頻播放器1.1版");//窗口標題

c=getContentPane();
c.setLayout(new BorderLayout());
//c.setBackground(new Color(40,40,95));

fileName=new Vector(1);
dirName=new Vector(1);
numList=new Vector(1);//構造三個容器用於支持播放清單
//vectorToString=new String[];
//prop=new Properties(System.getProperties());
//listIniAddress=prop.getProperty("user.dir")+"\\list.ini";
//listFile=new File(listIniAddress);//本來這些代碼用來取的系統屬性,後來
//發現根本就不用這么麻煩
listFile=new File("list.ini");//直接存於此目錄
Thread readToList=new Thread(this);//注意編線程程序的時候要注意運行的時候含有的變數億定義或者初始化,
//這就要求線程要等上述所說的情況下再運行,否則很容易發生錯誤或則異常

list=new JList();
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
list.setSelectionForeground(new Color(0,150,150));
list.setVisibleRowCount(10);
list.setFixedCellHeight(12);
list.setFixedCellWidth(250);
list.setFont(new Font("Serif",Font.PLAIN,12));
list.setBackground(new Color(40,40,95));
list.setForeground(new Color(0,128,255));
//list.setOpaque(false);
list.setToolTipText("點右鍵顯示更多功能");//創建播放清單並設置各個屬性
list.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
if (e.getClickCount() == 2) //判斷是否雙擊
{
index = list.locationToIndex(e.getPoint());//將滑鼠坐標轉化成list中的選項指針
createPlayer2();
//System.out.println("Double clicked on Item " + index);,此是測試的時候加的
}
}
/* public void mousePressed(MouseEvent e)
{
checkMenu(e);//自定義函數,判斷是否是右鍵,來決定是否顯示菜單
}*/
public void mouseReleased(MouseEvent e)
{
checkMenu(e);//與上面的一樣,判斷是否滑鼠右鍵
}

}
);
//listB=new JLabel(new ImageIcon("qingdan.gif"),SwingConstants.CENTER);
scroll=new JScrollPane(list);//用於存放播放列表
//dialog2=new JDialogTest(MediaPlayer.this,"播放清單",scroll);
//dialog2.setVisible(true);

readToList.start();//啟動先程,載入播放列表
try
{
Thread.sleep(10);
}
catch(InterruptedException e)
{
e.printStackTrace();
}

/*look=UIManager.getInstalledLookAndFeels();
try
{
UIManager.setLookAndFeel(look[2].getClassName());
SwingUtilities.updateComponentTreeUI(this);
}
catch(Exception e)
{
e.printStackTrace();
}*///與下面的代碼實現相同的功能,但執行速度要慢,原因:明顯轉了個大彎

/*try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e)
{
e.printStackTrace();
} *///此段代碼使執行速度大大降低

bar=new JMenuBar();
setJMenuBar(bar);//此兩行創建菜單欄並放到此窗口程序
//bar.setBackground(new Color(48,91,183));
fileMenu=new JMenu("文件");
bar.add(fileMenu);

choiceMenu=new JMenu("控制");
bar.add(choiceMenu);

aboutMenu=new JMenu("幫助");
bar.add(aboutMenu);

openItem =new JMenuItem("打開文件");
openDirItem =new JMenuItem("打開目錄");
closeItem =new JMenuItem("退出程序");
openItem.addActionListener(this);
openDirItem.addActionListener(this);
closeItem.addActionListener(this);
fileMenu.add(openItem);
fileMenu.add(openDirItem);
fileMenu.add(closeItem);

onTop=new JCheckBoxMenuItem("播放時位於最前面",top);
choiceMenu.add(onTop);
onTop.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
if(onTop.isSelected())
top=true;
else top=false;
setAlwaysOnTop(top);
}
}
);

choiceMenu.addSeparator();//加分割符號

buttonGroup=new ButtonGroup();
buttonValues=new JRadioButtonMenuItem[3];
for(int bt=0;bt<3;bt++)
{
buttonValues[bt]=new JRadioButtonMenuItem(content[bt]);
buttonGroup.add(buttonValues[bt]);
choiceMenu.add(buttonValues[bt]);
}
buttonValues[0].setSelected(true);
choiceMenu.addSeparator();

/*loopItem=new JCheckBoxMenuItem("是否循環");
choiceMenu.add(loopItem);
loopItem.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
loop=!loop;
}
}
);*/
infor=new JMenuItem("軟體簡介");
aboutMenu.add(infor);
infor.addActionListener(this);

about=new JMenuItem("關於作者");
about.addActionListener(this);
aboutMenu.add(about);
//菜單欄設置完畢

panel=new JPanel();
panel.setLayout(new BorderLayout());
c.add(panel,BorderLayout.CENTER);

panelSouth=new JPanel();
panelSouth.setLayout(new BorderLayout());
c.add(panelSouth,BorderLayout.SOUTH);

icon=new ImageIcon("icon\\Player.jpg");
label=new JLabel(icon);
panel.add(label);

popupMenu=new JPopupMenu();
del =new JMenuItem("刪除");//滑鼠右鍵彈出菜單對象實例化
popupMenu.add(del);
del.addActionListener(this);

delAll =new JMenuItem("全部刪除");
popupMenu.add(delAll);
delAll.addActionListener(this);
reName =new JMenuItem("重命名");
popupMenu.add(reName);
reName.addActionListener(this);

scroll=new JScrollPane(list);//用於存放播放列表
listB=new JLabel(new ImageIcon("icon\\qingdan.gif"),SwingConstants.CENTER);

panelSouth.add(listB,BorderLayout.NORTH);
panelSouth.add(scroll,BorderLayout.CENTER);

dialog1=new DialogDemo(MediaPlayer.this,"軟體說明");

this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);//設定窗口關閉方式
//this.setTitle("d");編譯通過,說明可以再次設定標題
this.setLocation(400,250);//設定窗口出現的位置
//this.setSize(350,320);//窗口大小
setSize(350,330);
this.setResizable(false);//設置播放器不能隨便調大小
this.setVisible(true);//此句不可少,否則窗口會不顯示

}

public void actionPerformed(ActionEvent e)
{
if(e.getSource()==openItem)//getSource()判斷發生時間的組鍵
{
//System.out.println("d");測試用
openFile();
//createPlayer();
//setTitle(title);

}
if(e.getSource()==openDirItem)//打開目錄
{
openDir();
}
if(e.getSource()==closeItem)//推出播放器
{
exity_n();
//System.exit(0);
}
if(e.getSource()==about)
{
JOptionPane.showMessageDialog(this,"此簡易播放器由計科0302\n"
+"harly\n "+" 完成 ",
"參與者",
JOptionPane.INFORMATION_MESSAGE);
}
if(e.getSource()==del)
{
//index
//delPaintList(index);
fileName.removeElementAt(indexForDel);
dirName.removeElementAt(indexForDel);
numList.removeAllElements();//從三個容器裡面移除此項
Enumeration enumFile=fileName.elements();
while(enumFile.hasMoreElements())
{
numList.addElement((numList.size()+1)+"."+enumFile.nextElement());
//numList添加元素,顯示播放里表中
}
//list.setListData(fileName);
list.setListData(numList);
if(index<indexForDel)
list.setSelectedValue(numList.elementAt(index),true);
else
{
if(index==indexForDel);
else
if(index!=0)
list.setSelectedValue(numList.elementAt(index-1),true);
}

//list.setSelectedIndex(index);
}

if(e.getSource()==delAll)//全部刪除
{
fileName.removeAllElements();
dirName.removeAllElements();
numList.removeAllElements();
list.setListData(numList);
}

if(e.getSource()==reName)//重命名
{
String name;//=JOptionPane.showInputDialog(this,"請輸入新的名字");
try
{
name=reNames();
fileName.setElementAt(name,indexForDel);
numList.setElementAt((indexForDel+1)+"."+name,indexForDel);
}
catch(ReName e2)//自定義的異常
{
}

}
if(e.getSource()==infor)
{
dialog1.setVisible(true);
}
}

public static void main(String[] args)
{
final MediaPlayer mp=new MediaPlayer();
mp.setIconImage(new ImageIcon("icon\\mPlayer.jpg").getImage());//改變默認圖標
mp.addWindowListener(new WindowAdapter()//注冊窗口事件
{
public void windowClosing(WindowEvent e)
{
//System.exit(0);
mp.exity_n();
}
}

);
System.out.println("注意:更新文件列表後,請先正常關閉播放器"
+"\n然後再關閉此DOS窗口,否則導致播放列表不能保存!!");
}

private void openFile()//為了界面原因,此代碼重寫,估計兼容性不好了
{
/*JFileChooser fileChooser=new JFileChooser();//文件選擇器
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);//可以選擇文件不能目錄
int result=fileChooser.showOpenDialog(this);//創建文件打開對話框,並設定此程序為父窗口監控*/

/*通過result的值來判斷文件是否打開成功
*JFileChooser類有很多靜態成員變數
**/
/*if(result==JFileChooser.CANCEL_OPTION)
{
file=null;//file已經在類中定義,如果選擇取消,file指向為空
}
else
{
file=fileChooser.getSelectedFile();//獲得文件對象
title=file.getAbsolutePath();//取得文件的絕對路徑並且賦給title設定標題
}*/
//if(fd==null)
//{
//String filename="java音頻播放器";
fd = new FileDialog(MediaPlayer.this);
//Filters fl=new Filters();
//fd.setFilenameFilter(fl);

fd.setVisible(true);
if (fd.getFile() != null)
{
title = fd.getDirectory() + fd.getFile();//原因請見同目錄下的FileDialogDemo.java文件
files=fd.getFile();
//dir =fd.getDirectory();
file=new File(title);
createPlayer();

}
//title=filename;
//fd=null;//缺少此句如果第一次打開文件的時候取消操作的時候第二次也不能打開文件了
//}
}
private void openDir()
{
JFileChooser fileChooser=new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result=fileChooser.showOpenDialog(MediaPlayer.this);
if(result==JFileChooser.CANCEL_OPTION)
return;
file=fileChooser.getSelectedFile();
if(file==null||file.getName().equals(""))
JOptionPane.showMessageDialog(this,"錯誤的路徑",
"出錯了",JOptionPane.ERROR_MESSAGE);
String[] sFiles=file.list();
for(int i=0;i<sFiles.length;i++)
{
fileName.addElement(sFiles[i]);
numList.addElement((numList.size()+1)+"."+sFiles[i]);
dirName.addElement(file.getAbsolutePath()+"\\"+sFiles[i]);
}
list.setListData(numList);

/*fd=new FileDialog(MediaPlayer.this);
fd.setVisible(true);
if(fd.getDirectory()!=null)
{
File fileDir=new File(fd.getDirectory());
String[] ss=fileDir.list();
for(int i=0;i<ss.length;i++)
{
System.out.println(ss[i]);
}
}*/
}
請採納答案,支持我一下。

Ⅲ 求JAVA視頻播放器代碼

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FileDialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.media.ControllerClosedEvent;
import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.media.EndOfMediaEvent;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.NoPlayerException;
import javax.media.Player;
import javax.media.PrefetchCompleteEvent;
import javax.media.RealizeCompleteEvent;
import javax.media.Time;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class JMFMediaPlayer extends JFrame implements ActionListener,
ControllerListener, ItemListener {
// JMF的播放器
Player player;
// 播放器的視頻組件和控制組件
Component vedioComponent;
Component controlComponent;
// 標示是否是第一次打開播放器
boolean first = true;
// 標示是否需要循環
boolean loop = false;
// 文件當前目錄
String currentDirectory;
// 構造方法
public JMFMediaPlayer(String title) {
super(title);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e){
// 用戶點擊窗口系統菜單的關閉按鈕
// 調用dispose以執行windowClosed
dispose();
}
public void windowClosed(WindowEvent e){
if (player != null){
// 關閉JMF播放器對象
player.close();
}
System.exit(0);
}
});
// 創建播放器的菜單
JMenu fileMenu = new JMenu("文件");
JMenuItem openMemuItem = new JMenuItem("打開");
openMemuItem.addActionListener(this);
fileMenu.add(openMemuItem);
// 添加一個分割條
fileMenu.addSeparator();
// 創建一個復選框菜單項
JCheckBoxMenuItem loopMenuItem = new JCheckBoxMenuItem("循環", false);
loopMenuItem.addItemListener(this);
fileMenu.add(loopMenuItem);
fileMenu.addSeparator();
JMenuItem exitMemuItem = new JMenuItem("退出");
exitMemuItem.addActionListener(this);
fileMenu.add(exitMemuItem);

JMenuBar menuBar = new JMenuBar();
menuBar.add(fileMenu);
this.setJMenuBar(menuBar);
this.setSize(200, 200);

try {
// 設置界面的外觀,為系統外觀
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
e.printStackTrace();
}
this.setVisible(true);
}
/**
* 實現了ActionListener介面,處理組件的活動事件
*/
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("退出")) {
// 調用dispose以便執行windowClosed
dispose();
return;
}
FileDialog fileDialog = new FileDialog(this, "打開媒體文件", FileDialog.LOAD);
fileDialog.setDirectory(currentDirectory);
fileDialog.setVisible(true);
// 如果用戶放棄選擇文件,則返回
if (fileDialog.getFile() == null){
return;
}
currentDirectory = fileDialog.getDirectory();
if (player != null){
// 關閉已經存在JMF播放器對象
player.close();
}
try {
// 創建一個打開選擇文件的播放器
player = Manager.createPlayer(new MediaLocator("file:"
+ fileDialog.getDirectory() + fileDialog.getFile()));
} catch (java.io.IOException e2) {
System.out.println(e2);
return;
} catch (NoPlayerException e2) {
System.out.println("不能找到播放器.");
return;
}
if (player == null) {
System.out.println("無法創建播放器.");
return;
}
first = false;
this.setTitle(fileDialog.getFile());
// 播放器的控制事件處理
player.addControllerListener(this);
// 預讀文件內容
player.prefetch();
}
/**
* 實現ControllerListener介面的方法,處理播放器的控制事件
*/
public void controllerUpdate(ControllerEvent e) {
// 調用player.close()時ControllerClosedEvent事件出現。
// 如果存在視覺部件,則該部件應該拆除(為一致起見,
// 我們對控制面板部件也執行同樣的操作)
if (e instanceof ControllerClosedEvent) {
if (vedioComponent != null) {
this.getContentPane().remove(vedioComponent);
this.vedioComponent = null;
}
if (controlComponent != null) {
this.getContentPane().remove(controlComponent);
this.controlComponent = null;
}
return;
}
// 如果是媒體文件到達尾部事件
if (e instanceof EndOfMediaEvent) {
if (loop) {
// 如果允許循環,則重新開始播放
player.setMediaTime(new Time(0));
player.start();
}
return;
}
// 如果是播放器預讀事件
if (e instanceof PrefetchCompleteEvent) {
// 啟動播放器
player.start();
return;
}
// 如果是文件打開完全事件,則顯示視頻組件和控制器組件
if (e instanceof RealizeCompleteEvent) {
vedioComponent = player.getVisualComponent();
if (vedioComponent != null){
this.getContentPane().add(vedioComponent);
}
controlComponent = player.getControlPanelComponent();
if (controlComponent != null){
this.getContentPane().add(controlComponent, BorderLayout.SOUTH);
}
this.pack();
}
}

// 處理「循環」復選框菜單項的點擊事件
public void itemStateChanged(ItemEvent e) {
loop = !loop;
}
public static void main(String[] args){
new JMFMediaPlayer("JMF媒體播放器");
}
}

試試吧,我這里運行正常

Ⅳ 如何用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();

}

}

}

Ⅳ 用java編寫多媒體播放器的代碼

這里是使用runtimegetRuntime().exec調用系統程序的代碼
Runtime.getRuntime().exec("C:/Program Files/Windows Media Player/wmplayer.exe");
Runtime.getRuntime().exec("C:/WINDOWS/system32/calc.exe");
這是調用系統播放器,嗯如果調用播放本地文件的話則用exec("","");
例如:Runtime.getRuntime().exec("D:/Program Files/TTPlayer/TTPlayer.exe E:/Kugou/祈求.mp3");

Ⅵ 求一個JAVA音樂播放器的源代碼

import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.media.EndOfMediaEvent;
import javax.media.PrefetchCompleteEvent;
import javax.media.RealizeCompleteEvent;
import javax.media.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MediaPlayer extends JFrame implements ActionListener,
ItemListener, ControllerListener {
String title;

Player player;
boolean first = true, loop = false;
Component vc, cc;
String currentDirectory=null;
// 構造函數,其中包括了設置響應窗口事件的監聽器。
MediaPlayer(String title) {
super(title);
/* 關閉按鈕的實現。。 */
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}

public void windowClosed(WindowEvent e) {
if (player != null)
player.close();
System.exit(0);
}

});
// 調用程序菜單欄的方法成員完成菜單的布置
setupMenu();
setSize(400, 400);
setVisible(true);
}

// 本方法用以設置程序菜單欄
public void setupMenu() {
// 設置一個菜單
Menu f = new Menu("文件");
// 往設置的菜單添加菜單項
MenuItem mi = new MenuItem("打開");
f.add(mi);
mi.addActionListener(this);
f.addSeparator();
CheckboxMenuItem cbmi = new CheckboxMenuItem("循環", false);
cbmi.addActionListener(this);
f.add(cbmi);
f.addSeparator();
MenuItem ee = new MenuItem("退出");
ee.addActionListener(this);
f.add(ee);
f.addSeparator();

Menu l = new Menu("播放列表");
Menu c = new Menu("播放控制");
MenuItem move = new MenuItem("播放");
move.addActionListener(this);
c.add(move);
c.addSeparator();
MenuItem pause = new MenuItem("暫停");
pause.addActionListener(this);
c.add(pause);
c.addSeparator();
MenuItem stop = new MenuItem("停止");
stop.addActionListener(this);
c.add(stop);
c.addSeparator();
// 設置一個菜單欄
MenuBar mb = new MenuBar();
mb.add(f);
mb.add?;
mb.add(l);
// 將構造完成的菜單欄交給當前程序的窗口;
setMenuBar(mb);
}

// 動作時間響應成員;捕捉發送到本對象的各種事件;
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String cufile, selectfile, currentDirectory;
if (e.getActionCommand().equals("退出")) {
// 調用dispose以便執行windowClosed
dispose();
return;
}
// 此事表明擁護選擇了「播放」命令;
// 如果當前有一個文件可以播放則執行播放命令;
if (e.getActionCommand().equals("播放")) {
if (player != null) {
player.start();
}
return;
}
// 如果當前正在播放某一文件,則執行暫停;
if (e.getActionCommand().equals("暫停")) {
if (player != null) {
player.stop();
}
return;
}
// 停止命令的響應;
if (e.getActionCommand().equals("停止")) {
if (player != null) {
player.stop();
player.setMediaTime(new Time(0));
}
return;
}
// 用戶選擇要播放的媒體文件
if (e.getActionCommand().equals("打開")) {
FileDialog fd = new FileDialog(this, "打開媒體文件", FileDialog.LOAD);
// fd.setDirectory(currentDirectory);

2008-2-6 02:46 回復

肆方茉莉
62位粉絲
6樓

fd.setVisible(true);
// 如果用戶放棄選擇文件,則返回
if (fd.getFile() == null) {
return;
}
// 保存了所選文件的名稱及其路徑名稱已被稍後使用
// 同時設置當前文件夾路徑
selectfile = fd.getFile();
currentDirectory = fd.getDirectory();
cufile = currentDirectory + selectfile;
// 將用戶選擇的文件作為一個菜單項加入播放列表,該菜單項名為該文件名;
// 被點擊後給出的命令串是該文件的全路徑名
MenuItem mi = new MenuItem(selectfile);
mi.setActionCommand(cufile);
MenuBar mb = getMenuBar();
Menu m = mb.getMenu(2);
mi.addActionListener(this);
m.add(mi);
} else {
// 程序邏輯運行到次表示用戶選擇了一個「播放列表」中的媒體文件
// 此時可以通過如下動作獲得該文件的全路徑名
cufile = e.getActionCommand();
selectfile = cufile;
}
// 如果存在一個播放器,則先將其關閉,稍後再重新創建
// 創建播放器時需要捕捉一些異常
if (player != null) {
player.close();
}
try {
player = Manager.createPlayer(new MediaLocator("file:" + cufile));
} catch (Exception e2) {
System.out.println(e2);
return;
}/*
* catch(NoPlayerException e2){ System.out.println("不能找到播放器");
* return ; }
*/
if (player == null) {
System.out.println("無法創建播放器");
return;
}
first = false;
setTitle(selectfile);
// 設置處理播放控制器實際的對象;
/**/
player.addControllerListener(this);
player.prefetch();
}

// 菜單狀態改變事件的響應函數;
public void itemStateChanged(ItemEvent arg0) {
// TODO Auto-generated method stub

}
public static void main(String[] args) {
// TODO Auto-generated method stub
new MediaPlayer("播放器");
}

// 調用繪圖函數進行界面的繪制 // public void update() {
// }
// 繪圖函數成員 //public void paint(Graphics g) {
// }
public void controllerUpdate(ControllerEvent e) {
// TODO Auto-generated method stub
Container tainer = getContentPane();
// 調用player.close()時ControllerClosedEvent事件出現
// 如果存在視覺部件,則該部件應該拆除(為了一致起見,我們對控制面版部件也執行同樣的操作,下一次需要時再構造)
if (e instanceof ControllerClosedEvent) {
if (vc != null) {
remove(vc);
vc = null;
}
if (cc != null) {
remove(cc);
cc = null;
}
}

// 播放結束時,將播放指針置於文件之首,如果設定了循環播放,則再次啟動播放器;
if (e instanceof EndOfMediaEvent) {
player.setMediaTime(new Time(0));
if (loop) {
player.start();
}
return;
}

// PrefetchCompletEvent事件發生後調用start,正式啟動播放
if (e instanceof PrefetchCompleteEvent) {
player.start();
return;
}

// 本事件表示由於播放的資源已經確定;此時要將媒體的圖形conmopnent
// 如果有顯示出來,同時將播放器player的控制顯示到窗口裡;
if (e instanceof RealizeCompleteEvent) {
// 如果媒體中有圖像,將對應圖像component載入窗體;
vc = player.getVisualComponent();
if (vc != null)
tainer.add(vc, BorderLayout.CENTER);
// 將對應控制器component載入窗體;
cc = player.getControlPanelComponent();
cc.setBackground(Color.blue);
if (cc != null)
tainer.add(cc, BorderLayout.SOUTH);
// 有一些特殊媒體在播放時提供另外的控制手段,將控制器一並加入窗口;
/*
* gc=player.getGainControl(); gcc=gc.getControlComponent();
* if(gcc!=null) tainer.add(gcc,BorderLayout.NORTH);
*/
// 根據媒體文件中是否有圖像,設定相應的窗口大小
if (vc != null) {
pack();
return;
} else {
setSize(300, 75);
setVisible(true);
return;
}
}

} }

熱點內容
淘寶圖片緩存怎麼關閉 發布:2025-08-21 09:51:31 瀏覽:149
訪問學者出國手續 發布:2025-08-21 09:51:26 瀏覽:365
91資源解壓 發布:2025-08-21 09:42:14 瀏覽:415
創新科存儲技術 發布:2025-08-21 09:42:12 瀏覽:891
我的世界十三區伺服器地址 發布:2025-08-21 09:41:28 瀏覽:432
編程語言排行榜2016 發布:2025-08-21 09:31:33 瀏覽:295
編程教學廣告 發布:2025-08-21 09:28:24 瀏覽:173
安卓手機用哪個軟體編輯視頻 發布:2025-08-21 09:25:02 瀏覽:577
邁騰最低配有哪些值得選裝的配置 發布:2025-08-21 09:14:04 瀏覽:836
php求職 發布:2025-08-21 09:14:03 瀏覽:490