当前位置:首页 > 代码 > 正文

java播放器源代码(视频播放器源代码)

admin 发布:2022-12-19 16:31 113


今天给各位分享java播放器源代码的知识,其中也会对视频播放器源代码进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

如何用java做一个音乐播放器?

看看其它网友的答案:

首先下载播放mp3的包,比如mp3spi1.9.4.jar。在工程中添加这个包。

播放器演示代码如下

package com.test.audio;

import java.io.File;

import java.awt.BorderLayout;

import java.awt.FileDialog;

import java.awt.Frame;

import java.awt.GridLayout;

import java.awt.Label;

import java.awt.List;

import java.awt.Menu;

import java.awt.MenuBar;

import java.awt.MenuItem;

import java.awt.MenuShortcut;

import java.awt.Panel;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.KeyEvent;

import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import javax.sound.sampled.AudioFormat;

import javax.sound.sampled.AudioInputStream;

import javax.sound.sampled.AudioSystem;

import javax.sound.sampled.DataLine;

import javax.sound.sampled.SourceDataLine;

public class MusicPlayer extends Frame {

/**

*

*/

private static final long serialVersionUID = -2605658046194599045L;

boolean isStop = true;// 控制播放线程

boolean hasStop = true;// 播放线程状态

String filepath;// 播放文件目录

String filename;// 播放文件名称

AudioInputStream audioInputStream;// 文件流

AudioFormat audioFormat;// 文件格式

SourceDataLine sourceDataLine;// 输出设备

List list;// 文件列表

Label labelfilepath;//播放目录显示标签

Label labelfilename;//播放文件显示标签

public MusicPlayer() {

// 设置窗体属性

setLayout(new BorderLayout());

setTitle("MP3 Music Player");

setSize(350, 370);

// 建立菜单栏

MenuBar menubar = new MenuBar();

Menu menufile = new Menu("File");

MenuItem menuopen = new MenuItem("Open", new MenuShortcut(KeyEvent.VK_O));

menufile.add(menuopen);

menufile.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

open();

}

});

menubar.add(menufile);

setMenuBar(menubar);

// 文件列表

list = new List(10);

list.addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent e) {

// 双击时处理

if (e.getClickCount() == 2) {

// 播放选中的文件

filename = list.getSelectedItem();

play();

}

}

});

add(list, "Center");

// 信息显示

Panel panel = new Panel(new GridLayout(2, 1));

labelfilepath = new Label("Dir:");

labelfilename = new Label("File:");

panel.add(labelfilepath);

panel.add(labelfilename);

add(panel, "North");

// 注册窗体关闭事件

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

setVisible(true);

}

// 打开

private void open() {

FileDialog dialog = new FileDialog(this, "Open", 0);

dialog.setVisible(true);

filepath = dialog.getDirectory();

if (filepath != null) {

labelfilepath.setText("Dir:" + filepath);

// 显示文件列表

list.removeAll();

File filedir = new File(filepath);

File[] filelist = filedir.listFiles();

for (File file : filelist) {

String filename = file.getName().toLowerCase();

if (filename.endsWith(".mp3") || filename.endsWith(".wav")) {

list.add(filename);

}

}

}

}

// 播放

private void play() {

try {

isStop = true;// 停止播放线程

// 等待播放线程停止

System.out.print("Start:" + filename);

while (!hasStop) {

System.out.print(".");

try {

Thread.sleep(10);

} catch (Exception e) {

}

}

System.out.println("");

File file = new File(filepath + filename);

labelfilename.setText("Playing:" + filename);

// 取得文件输入流

audioInputStream = AudioSystem.getAudioInputStream(file);

audioFormat = audioInputStream.getFormat();

// 转换mp3文件编码

if (audioFormat.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {

audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,

audioFormat.getSampleRate(), 16, audioFormat

.getChannels(), audioFormat.getChannels() * 2,

audioFormat.getSampleRate(), false);

audioInputStream = AudioSystem.getAudioInputStream(audioFormat,

audioInputStream);

}

// 打开输出设备

DataLine.Info dataLineInfo = new DataLine.Info(

SourceDataLine.class, audioFormat,

AudioSystem.NOT_SPECIFIED);

sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);

sourceDataLine.open(audioFormat);

sourceDataLine.start();

// 创建独立线程进行播放

isStop = false;

Thread playThread = new Thread(new PlayThread());

playThread.start();

} catch (Exception e) {

e.printStackTrace();

}

}

class PlayThread extends Thread {

byte tempBuffer[] = new byte[320];

public void run() {

try {

int cnt;

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 (Exception e) {

e.printStackTrace();

System.exit(0);

}

}

}

public static void main(String args[]) {

new MusicPlayer();

}

}

求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;bt3;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(indexindexForDel)

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;isFiles.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;iss.length;i++)

{

System.out.println(ss[i]);

}

}*/

}

请采纳答案,支持我一下。

求一个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;

}

}

} }

求音乐播放器java源程序

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

import java.net.*;

import javax.swing.*;

import java.io.File;

class AudioPlayDemo extends JFrame implements ActionListener {

boolean looping = false;

File file1 = new File("music\\明天会更好.wav");

AudioClip sound1;

AudioClip chosenClip;

JButton playButton = new JButton("播放");

JButton loopButton = new JButton("循环播放");

JButton stopButton = new JButton("停止");

JLabel status = new JLabel("选择播放文件");

JPanel controlPanel = new JPanel();

Container container = getContentPane();

public AudioPlayDemo() {

try {

sound1 = Applet.newAudioClip(file1.toURL());

chosenClip = sound1;

} catch(OutOfMemoryError e){

System.out.println("内存溢出");

e.printStackTrace();

} catch(Exception e){

e.printStackTrace();

}

playButton.addActionListener(this);

loopButton.addActionListener(this);

stopButton.addActionListener(this);

stopButton.setEnabled(false);

controlPanel.add(playButton);

controlPanel.add(loopButton);

controlPanel.add(stopButton);

container.add(controlPanel, BorderLayout.CENTER);

container.add(status, BorderLayout.SOUTH);

setSize(300, 130);

setVisible(true);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序

}

public void actionPerformed(ActionEvent event) {

if (chosenClip == null) {

status.setText("声音未载入");

return;

}

Object source = event.getSource(); //获取用户洗涤激活的按钮

if (source == playButton) {

stopButton.setEnabled(true);

loopButton.setEnabled(true);

chosenClip.play();

status.setText("正在播放");

}

if (source == loopButton) {

looping = true;

chosenClip.loop();

loopButton.setEnabled(false);

stopButton.setEnabled(true);

status.setText("正在循环播放");

}

if (source == stopButton) {

if (looping) {

looping = false;

chosenClip.stop();

loopButton.setEnabled(true);

} else {

chosenClip.stop();

}

stopButton.setEnabled(false);

status.setText("停止播放");

}

}

public static void main(String s[]) {

new AudioPlayDemo();

}

}

这功能不齐,不能下载,也不能播放mp3格式音乐,是用来播放wav格式音乐的,(但你可以在千千静听里把mp3格式转换为wav格式)

打字不易,如满意,望采纳。

求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播放器源代码和视频播放器源代码的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。

版权说明:如非注明,本站文章均为 AH站长 原创,转载请注明出处和附带本文链接;

本文地址:http://ahzz.com.cn/post/13159.html


取消回复欢迎 发表评论:

分享到

温馨提示

下载成功了么?或者链接失效了?

联系我们反馈

立即下载