导航:首页 > 编程语言 > 音乐播放器java代码

音乐播放器java代码

发布时间:2023-06-29 21:55:00

1. 基于android音乐播放器源代码(正常播放、有列表)

package my.android.players;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;

public class mainActivity extends Activity {

private List<String> myMusicList=new ArrayList<String>();
//当前播放歌曲的索引
private int currentListItem=0;
//音乐的路径
private static final String MUSIC_PATH="/sdcard/mp3";
//播放对象
private MediaPlayer myMediaPlayer;
private TextView m_TextView;
//播放按钮
private ImageButton m_start;
private ImageButton m_stop;
private ImageButton m_next;
private ImageButton m_last;
/*设定bIsPaused一开始为false */
private boolean bIsRun = false;
private boolean isplay;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);

myMediaPlayer=new MediaPlayer();

musicList();
m_TextView=(TextView)findViewById(R.id.mtextview);
m_start=(ImageButton)findViewById(R.id.imgbtn_start);
m_stop=(ImageButton)findViewById(R.id.imgbtn_stop);
m_next=(ImageButton)findViewById(R.id.imgbtn_next);
m_last=(ImageButton)findViewById(R.id.imgbtn_last);
listener();

Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
currentListItem = bundle.getInt("currentListItem");
isplay=bundle.getBoolean("isplay");
if(isplay==true)
{
bIsRun=false;
playMusic(MUSIC_PATH+"/"+myMusicList.get(currentListItem));
}
}
//监听事件
void listener(){

//开始
m_start.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
if(myMediaPlayer.isPlaying()==true)
{
myMediaPlayer.pause();
m_start.setImageResource(R.drawable.pause);
}
else
{
playMusic(MUSIC_PATH+"/"+myMusicList.get(currentListItem));
}

}
catch (IllegalStateException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

}
});
//下一首
m_next.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
nextMusic();
}
});

//上一首
m_last.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

lastMusic();
}
});

//停止
m_stop.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopMusic();
}
});

myMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
nextMusic();
}
});
}
//播放音乐
void playMusic(String path){
try {
if(bIsRun==false)
{
myMediaPlayer.reset();
myMediaPlayer.setDataSource(path);
myMediaPlayer.prepare();
myMediaPlayer.start();
/*
* 取出歌曲名的.mp3后缀
* */
String str=(myMusicList.get(currentListItem)).toString();
System.out.println(str);
String str1[]=str.split("\\.");
System.out.println(str1[0]);
m_TextView.setText(str1[0]);
}
else
{
myMediaPlayer.start();
}
m_start.setImageResource(R.drawable.start);
bIsRun=true;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}

//下一首
void nextMusic(){
if(++currentListItem>=myMusicList.size()){
currentListItem=0;
}
bIsRun=false;
playMusic(MUSIC_PATH+"/"+myMusicList.get(currentListItem));
}

//上一首
void lastMusic(){
if(--currentListItem<0)
currentListItem=myMusicList.size()-1;
bIsRun=false;
playMusic(MUSIC_PATH+"/"+myMusicList.get(currentListItem));
}
//停止
void stopMusic() {

if (myMediaPlayer.isPlaying()) {
m_start.setImageResource(R.drawable.pause);
myMediaPlayer.stop();// 停止
bIsRun=false;
}
else
playMusic(MUSIC_PATH+"/"+myMusicList.get(currentListItem));
}
//当用户返回时结束音乐并释放音乐对象
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if(keyCode==KeyEvent.KEYCODE_BACK){
new AlertDialog.Builder(mainActivity.this).setTitle("message")
.setIcon(android.R.drawable.dialog_frame)
.setMessage("你确定要离开吗?")
.setPositiveButton("确定",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
myMediaPlayer.stop();
myMediaPlayer.release();
finish();
}
}).setNegativeButton("取消",new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub

}
}).show();

}
return super.onKeyDown(keyCode, event);
}
/**
* 文件过滤器
*
* @author
*
*/
class MusicFilter implements FilenameFilter {

@Override
public boolean accept(File dir, String filename) {

return (filename.endsWith(".mp3"));
}

}
//绑定音乐
void musicList(){
try{
File home=new File(MUSIC_PATH);
if(!home.exists())
home.mkdirs();
if(home.listFiles(new MusicFilter()).length>=0){
for(File file:home.listFiles(new MusicFilter())){
myMusicList.add(file.getName().toString());
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}

package my.android.players;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import android.widget.ListView;

public class Activity01 extends Activity {

//播放列表
private List<String> myMusicList=new ArrayList<String>();
//当前播放歌曲的索引
private int currentListItem;
//音乐的路径
private static final String MUSIC_PATH="/sdcard/mp3";
//播放列表
private ListView m_ListView;

private boolean isplay=true;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

m_ListView=(ListView)findViewById(R.id.lv_music);

musicList();

//当选择列表项时播放音乐
m_ListView.setOnItemClickListener(new ListView.OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
currentListItem = arg2;
Intent intent = new Intent();
Bundle mBundle=new Bundle();
mBundle.putInt("currentListItem", currentListItem);
mBundle.putBoolean("isplay", isplay);
intent.putExtras(mBundle);
intent.setClass(Activity01.this,mainActivity.class);
startActivity(intent);
finish();
}
});
}

/**
* 文件过滤器
*
* @author
*
*/
class MusicFilter implements FilenameFilter {

@Override
public boolean accept(File dir, String filename) {

return (filename.endsWith(".mp3"));
}

}

//绑定音乐
void musicList(){
try{
File home=new File(MUSIC_PATH);
if(!home.exists())
home.mkdirs();
if(home.listFiles(new MusicFilter()).length>=0){
for(File file:home.listFiles(new MusicFilter())){
myMusicList.add(file.getName().toString());
}
ArrayAdapter<String> musicList=new ArrayAdapter<String>
(Activity01.this,android.R.layout.simple_list_item_1, myMusicList);
m_ListView.setAdapter(musicList);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}

2. 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代码相关的资料

热点内容
php实现投票 浏览:331
手机爆力解压加密视频文件 浏览:930
东方财富app怎么看北上资金图解 浏览:416
邢昭林程序员那么可爱拍现场 浏览:169
安卓什么应用可以免费看电视剧 浏览:504
合适pdf 浏览:293
app监测睡眠怎么选择 浏览:642
老人家用什么安卓手机好 浏览:955
解压包能不能送女朋友 浏览:701
好看发卡网源码 浏览:51
水平集算法matlab 浏览:768
局域网如何用ftp服务器配置 浏览:72
程序员惯性思考模式 浏览:441
如何在个税app上查身份证号 浏览:6
电视家app安装在电视上怎么安 浏览:889
怎么将pdf格式转化为图片格式 浏览:638
服务器拔掉raid卡怎么装系统 浏览:233
区域对称加密算法 浏览:247
数字转汉字php 浏览:735
安卓源码硬件驱动 浏览:210