安卓音乐播放器开发,含源代码

合集下载

Android应用开发--MP3简单音乐播放器

Android应用开发--MP3简单音乐播放器

Android应用开发--MP3简单音乐播放器点击列表会进入播放的Activity,在这个Activity会接收到从前面的Activity传来的数据,在通过这些数据来启动服务来播放音乐,整个过程很简单,需要注意的是我们要接收的数据是哪些内容,还有我们向Service要传什么样的数据,这是根据自己的开发思路和需求来决定的,等一下你们会看到小鬼到底往Service传了些什么东西,然而这些数据到底起什么作用,需要慢慢去体会,因为这是需要一点一点去调试的。

好了,下面贴一下整个Activity的实现代码,主要是播放的各种状态的实现,因为这个音乐播放器并没有完全开发完,所以朋友们需要弄清楚这一点。

如果对代码的实现有不清楚的,可以给小鬼留言,小鬼有空一定给大家解答。

效果如下:代码如下:package com.anjovo.as.chapter10.exam01;import java.io.IOException;import android.media.AudioManager;import android.media.MediaPlayer;import .Uri;import android.os.Bundle;import android.app.Activity;import android.content.Intent;import android.view.ContextMenu;import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu;import android.view.MenuItem;import android.view.SubMenu;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast;public class MusicPlayerActivity extends Activity {protected static final int REQUEST_CODE = 1;private Button btnPlay,btnPause,baStop,back;private ImageView image;private TextView text;private MediaPlayer player;int position = 0;//声明一个变量判断是否为播放,默认为falseprivate boolean isPaused = false,Media=false;@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);setContentView(yout.activity_music_player);btnPlay = (Button) findViewById(R.id.bt_play);btnPause = (Button) findViewById(R.id.bt_pause);baStop = (Button) findViewById(R.id.bt_stop);back = (Button) findViewById(R.id.bt_back);image = (ImageView)findViewById(R.drawable.ic_launcher);text = (TextView) findViewById(R.id.text);image = (ImageView) findViewById(R.drawable.fengcun);registerForContextMenu(baStop);//注册,让这个bastop将会启用上下文菜单text.setText("歌词下载错误!");final Intent serintent = newIntent(this,newActivity.class);btnPause.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubstartActivityForResult(serintent,REQUEST_CODE);}});back.setOnClickListener(new Button.OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubfinish();if(Media==true){player.stop();player.release();}}});}public void BlooeanMedia(){if(Media==true){player.release();}}public void Player(MediaPlayer player){ try {if(player!=null){player.stop();}player.prepare();player.start();isPaused = true;Media=true;Toast.makeText(this, "音乐播放中...", Toast.LENGTH_LONG).show();} catch (IllegalStateException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}@Overridepublic boolean onContextItemSelected(MenuItem item) { // TODO Auto-generated method stubswitch(item.getItemId()){case 1:/** 用户点击了Id为“1”的子项,在这里编写处理代码*/BlooeanMedia();player = MediaPlayer.create(this,R.raw.wintersecret);MediaPlayer(player);Player(player);text.setText("周传雄-冬天的秘密...");break;case 2:/** 用户点击了Id为“2”的子项,在这里编写处理代码*/BlooeanMedia();player = MediaPlayer.create(this, R.raw.after);MediaPlayer(player);Player(player);text.setText("庄心研-以后的以后...");break;case 3:/** 用户点击了Id为“2”的子项,在这里编写处理代码*/BlooeanMedia();player = MediaPlayer.create(this, R.raw.baby);MediaPlayer(player);Player(player);text.setText("张悬-宝贝...");break;case 4:/** 用户点击了Id为“2”的子项,在这里编写处理代码*/BlooeanMedia();player = MediaPlayer.create(this, R.raw.lovegirl);MediaPlayer(player);Player(player);text.setText("张赫宣-你是我心爱的姑娘...");break;case 5:/** 用户点击了Id为“2”的子项,在这里编写处理代码*/Toast.makeText(this, "Item 5被选择",Toast.LENGTH_LONG).show();break;case 6:/** 用户点击了Id为“2”的子项,在这里编写处理代码*/Toast.makeText(this, "Item 6被选择",Toast.LENGTH_LONG).show();break;case 7:/** 用户点击了Id为“2”的子项,在这里编写处理代码*/Toast.makeText(this, "Item 7被选择",Toast.LENGTH_LONG).show();break;case 8:/** 用户点击了Id为“2”的子项,在这里编写处理代码*/Toast.makeText(this, "Item 8被选择",Toast.LENGTH_LONG).show();break;case 9:/** 用户点击了Id为“2”的子项,在这里编写处理代码*/Toast.makeText(this, "Item 9被选择",Toast.LENGTH_LONG).show();break;case 10:/** 用户点击了Id为“2”的子项,在这里编写处理代码*/Toast.makeText(this, "Item 10被选择",Toast.LENGTH_LONG).show();break;}return super.onOptionsItemSelected(item);}private void MediaPlayer(final MediaPlayer player) { // TODO Auto-generated method stub//增加播放音乐按钮的事件btnPlay.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubtry {if(player!=null){if(isPaused==false){player.start();isPaused=true;Toast.makeText(getApplicationContext(), "音乐播放中...", Toast.LENGTH_LONG).show();}else if(isPaused==true){player.pause();//暂停isPaused=false;Toast.makeText(getApplicationContext(), "音乐暂停中...", Toast.LENGTH_LONG).show();}}player.prepare();//同步地准备播放或回放player.start();//开始播放} catch (IllegalStateException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}});//播放完毕player.setOnCompletionListener(newMediaPlayer.OnCompletionListener() {@Overridepublic void onCompletion(MediaPlayer arg0) {// TODO Auto-generated method stubtry{//释放dtmimi.mp3这个资源,让它可被其它播放器使用player.release();//释放MediaPlayerToast.makeText(getApplicationContext(), "音乐播放结束!", Toast.LENGTH_LONG).show();text.setText("");}catch(Exception e){Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();e.printStackTrace();}}});//播放出错的处理player.setOnErrorListener(newMediaPlayer.OnErrorListener() {@Overridepublic boolean onError(MediaPlayer arg0, int arg1, int arg2) {// TODO Auto-generated method stubtry{//发生错误时也释放资源player.release();Toast.makeText(getApplicationContext(), "播放发生异常!", Toast.LENGTH_LONG).show();}catch(Exception e){Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_LONG).show();e.printStackTrace();}return false;}});}@Overridepublic void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {// TODO Auto-generated method stubsuper.onCreateContextMenu(menu, v, menuInfo);menu.add(Menu.NONE, 1, Menu.NONE, "周传雄-冬天的秘密");menu.add(Menu.NONE, 2, Menu.NONE, "庄心研-以后的以后");menu.add(Menu.NONE, 3, Menu.NONE, "张悬-宝贝");menu.add(Menu.NONE, 4, Menu.NONE, "张赫宣-你是我心爱的姑娘");menu.add(Menu.NONE, 5, Menu.NONE, R.string.menu_item5);//将Item6设置为子菜单SubMenu subMenu = menu.addSubMenu(Menu.NONE, 6, Menu.NONE, R.string.menu_item6);subMenu.setHeaderIcon(R.drawable.ic_launcher);subMenu.setIcon(R.drawable.ic_launcher);subMenu.setHeaderTitle("子菜单");subMenu.add(Menu.NONE, 7, Menu.NONE,R.string.menu_item7);subMenu.add(Menu.NONE, 8, Menu.NONE,R.string.menu_item8);subMenu.add(Menu.NONE, 9, Menu.NONE,R.string.menu_item9);subMenu.add(Menu.NONE, 10, Menu.NONE,R.string.menu_item10);}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {// TODO Auto-generated method stubsuper.onActivityResult(requestCode, resultCode, data);if(requestCode==REQUEST_CODE&&resultCode==RESULT_OK){ if(data!=null){//通过data参数处理返回信息String info = data.getData().toString();Uri myUri = Uri.parse(info);//将传回来的路径放在myUri中BlooeanMedia();player = new MediaPlayer();MediaPlayer(player);player.setAudioStreamType(AudioManager.STREAM_MUSIC);try {player.setDataSource(getApplicationContext(),myUri);//按地址播放player.prepare();player.start();isPaused = true;Media=true;Toast.makeText(this, "音乐播放中...", Toast.LENGTH_LONG).show();} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SecurityException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalStateException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}else{Toast.makeText(this, "无返回信息",Toast.LENGTH_SHORT).show();}}}}package com.anjovo.as.chapter10.exam01;import java.io.File;import java.util.ArrayList;import java.util.List;import android.app.Activity;import android.content.Intent;import .Uri;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.Button;import android.widget.EditText;import android.widget.ListView;import android.widget.Toast;/*** 使用一个包含String的List作为ListView的数据源,由于要在匿名内部类的方法中* 使用它,故将其定义为类的属性*/public class newActivity extends Activity{private List<String> dataList;private List<String> datauri;private String m_path;@Overrideprotected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(yout.array_adapter_acyivity);ListView list = (ListView) findViewById(R.id.list);dataList = new ArrayList<String>();datauri = new ArrayList<String>();m_path = new String("mnt/sdcard/");search(m_path, ".mp3", dataList,datauri);//定义一个ArrayAdapter,将数据源——dataList中的内容添加到这个ArrayAdapter//中,第二个参数指每一项将使用的界面布局final ArrayAdapter<String> adapter = newArrayAdapter<String>(this, yout.array_adapter_item, dataList);list.setAdapter(adapter);//将ArrayAdapter填充到ListView//处理用户单击选择的事件list.setOnItemClickListener(newAdapterView.OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view, int position,long id) {// TODO Auto-generated method stubIntent intent = new Intent();String url = datauri.get(position);intent.setData(Uri.parse(url));setResult(RESULT_OK, intent);finish();}});//处理用户长按事件list.setOnItemLongClickListener(newAdapterView.OnItemLongClickListener() {@Overridepublic boolean onItemLongClick(AdapterView<?> parent, View view,int position, long id) {// TODO Auto-generated method stubToast.makeText(getApplicationContext(),dataList.get(posit ion)+"删除成功!", Toast.LENGTH_LONG).show();//用户长按一项时,删除这一项内容dataList.remove(position);//通知Adapter的观察者数据源改变了,界面内容也得发生改变adapter.notifyDataSetChanged();return true; //返回true表示长按}});}}布局文件如下:<RelativeLayoutxmlns:android="/apk/res/and roid"xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:paddingBottom="@dimen/activity_vertical_margi n"android:paddingLeft="@dimen/activity_horizontal_margi n"android:paddingRight="@dimen/activity_horizontal_marg in"android:paddingTop="@dimen/activity_vertical_margin"tools:context=".MusicPlayerActivity"><Buttonandroid:id="@+id/bt_pause"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentBottom="true"android:layout_alignParentLeft="true"android:layout_marginBottom="14dp"android:text="列表"/><Buttonandroid:id="@+id/bt_play"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignBaseline="@+id/bt_pause"android:layout_alignBottom="@+id/bt_pause"android:layout_centerHorizontal="true"android:text="播放"/><Buttonandroid:id="@+id/bt_back"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignLeft="@+id/bt_stop"android:layout_alignParentTop="true"android:text="返回"/><Buttonandroid:id="@+id/bt_stop"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignBaseline="@+id/bt_play"android:layout_alignBottom="@+id/bt_play"android:layout_toRightOf="@+id/image"android:text="选择"/><ImageViewandroid:id="@+id/image"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_above="@+id/text"android:layout_marginBottom="16dp"android:layout_toRightOf="@+id/bt_pause"android:src="@drawable/fengcun"/><TextViewandroid:id="@+id/text"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_above="@+id/bt_play"android:layout_centerHorizontal="true"android:layout_marginBottom="48dp"android:text="."/> </RelativeLayout>。

Androidstudio简单的音乐播放器实现

Androidstudio简单的音乐播放器实现

Androidstudio简单的音乐播放器实现JAVA文件:MainActivity.java,menuActivity.java,Music.java,PreActivity.javaXML文件:activity_main.xml,activity_pre.xml,activity_menu.xml在PreActivity.java文件中,程序主要执行开启线程,实现开启软件进入欢迎界面,并在1秒后自动跳转到音乐播放器主界面,界面在activity_pre.xml文件中实现。

PreActivity.javapublic class PreActivity extends Activity {Handler handler=new Handler(){public void handleMessage(Message msg){if(msg.what==250){Intent intent=new Intent(PreActivity.this,MainActivity.class);startActivity(intent);finish();}};};@Overrideprotected void onCreate(Bundle savedInstanceState){//TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(yout.activity_pre); //加载布局WaitThread thread=new WaitThread(); //开启线程thread.start();}public class WaitThread extends Thread{ //创建线程@Overridepublic void run(){//TODO Auto-generated method stubtry{Thread.sleep(1000);}catch (InterruptedException e){//TODO Auto-generated catch blocke.printStackTrace();}Message message=new Message();message.what=250;message.arg1=1;handler.sendMessage(message);}}}activity_pre.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android=""android:layout_width="400dp"android:layout_height="800dp"android:background="#ffffff"android:orientation="vertical"android:weightSum="1"><ImageViewandroid:src="@drawable/welcome"android:layout_width="408dp"android:layout_height="451dp"android:layout_weight="0.77" /></LinearLayout>主要功能实现MainActivity.java,音乐播放器主界面activity_main.xml。

安卓音乐播放器开发,含源代码

安卓音乐播放器开发,含源代码

基于android平台的音乐播放器开发实验报告For personal use only in study and research; not for commercial use学生姓名:温从林学号:0215班级:计自1201第一章引言1.1 项目背景当今社会的生活节奏越来越快,人们对手机的要求也越来越高,由于手机市场发展迅速,使得手机操作系统也出现了不同各类,现在的市场上主要有三个手机操作系统,Windows mobile,symbian,以及谷歌的Android操作系统,其中占有开放源代码优势的Android系统有最大的发展前景。

那么能否在手机上拥有自己编写的个性音乐播放器呢?能的,谷歌Android系统就能做到。

本文的音乐播放器就是基于谷歌Android手机平台的播放器。

Android:是谷歌于2007年公布的开放式源代码手机系统,它的开放性就优于其它封闭式的手机系统,因此,任何人都可能根据自己的喜好将手机系统中的所有功能重新编写。

这使得越来越多的人关注这个操作系统。

本次作品音乐播放器就是基于Android平台的。

1.2 编写目的现今社会生活紧张,而欣赏音乐是其中最好的舒缓压力的方式之一,本项目的目的是开发一个可以播放主流音乐文件格式的播放器,本设计实现的主要功能是播放Mp3,Wav多种格式的音乐文件,并且能够控制播放,暂停,停止,播放列等基本播放控制功能,界面简明,操作简单。

本项目是一款基于Android手机平台的音乐播放器,使Android手机拥有个性的多媒体播放器,使手机显得更生动灵活化,与人们更为接近,让手机主人随时随地处于音乐视频的旋律之中。

使人们的生活更加多样化。

也使设计者更加熟练Android的技术和其它在市场上的特点。

1.3 开发环境Eclipse、Android SDK 3.2.0第二章系统需求分析2.1 功能需求(用例图分析)根据项目的目标,我们可获得项目系统的基本需求,以下从不同角度来描述系统的需求,并且使用用例图来描述,系统的功能需求,我们分成四部分来概括,即播放器的基本控制需要,播放列表管理需求,播放器友好性需求和播放器扩展卡需求。

Android下MP3播放器的实现源代码

Android下MP3播放器的实现源代码

MusicInfoController.javapackage com.yarin.android.MusicPlayer;import android.content.ContentResolver;import android.database.Cursor;import .Uri;import android.provider.MediaStore;public class MusicInfoController{private static MusicInfoController mInstance = null;private MusicPlayerApp pApp = null;public static MusicInfoController getInstance(MusicPlayerApp app){if (mInstance == null){mInstance = new MusicInfoController(app);}return mInstance;}private MusicInfoController(MusicPlayerApp app){pApp = app;}public MusicPlayerApp getMusicPlayer(){return pApp;}private Cursor query(Uri uri, String[] prjs, String selections, String[] selectArgs, String order){ ContentResolver resolver = pApp.getContentResolver();if (resolver == null){return null;}return resolver.query(uri, prjs, selections, selectArgs, order);}public Cursor getAllSongs(){return query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);MusicList.javapackage com.yarin.android.MusicPlayer;import android.app.ListActivity;import android.content.BroadcastReceiver;import ponentName;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.content.ServiceConnection;import android.database.Cursor;import android.os.Bundle;import android.os.IBinder;import android.provider.MediaStore;import android.view.View;import android.widget.Button;import android.widget.ListAdapter;import android.widget.ListView;import android.widget.SimpleCursorAdapter;import android.widget.T extView;public class MusicList extends ListActivity{private MusicPlayerService mMusicPlayerService = null;private MusicInfoController mMusicInfoController = null;private Cursor mCursor = null;private TextView mTextView = null;private Button mPlayPauseButton = null;private Button mStopButton = null;private ServiceConnection mPlaybackConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { mMusicPlayerService = ((MusicPlayerService.LocalBinder)service).getService();}public void onServiceDisconnected(ComponentName className){ mMusicPlayerService = null;}};protected BroadcastReceiver mPlayerEvtReceiver = new BroadcastReceiver() { @Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();if (action.equals(MusicPlayerService.PLAYER_PREPARE_END)) {// will begin to playmTextView.setVisibility(View.INVISIBLE); mPlayPauseButton.setVisibility(View.VISIBLE);mStopButton.setVisibility(View.VISIBLE);mPlayPauseButton.setText(R.string.pause);} else if(action.equals(MusicPlayerService.PLAY_COMPLETED)){ mPlayPauseButton.setText(R.string.play);}}};public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.list_layout);MusicPlayerApp musicPlayerApp=(MusicPlayerApp)getApplication(); mMusicInfoController =(musicPlayerApp).getMusicInfoController();// bind playback servicestartService(new Intent(this,MusicPlayerService.class));bindService(new Intent(this,MusicPlayerService.class), mPlaybackConnection,Context.BIND_AUTO_CREATE);mTextView = (TextView)findViewById(R.id.show_text); mPlayPauseButton = (Button)findViewById(R.id.play_pause_btn); mStopButton = (Button) findViewById(R.id.stop_btn);mPlayPauseButton.setOnClickListener(new Button.OnClickListener() {public void onClick(View v) {// Perform action on clickif (mMusicPlayerService != null && mMusicPlayerService.isPlaying()) { mMusicPlayerService.pause();mPlayPauseButton.setText(R.string.play);} else if (mMusicPlayerService != null){mMusicPlayerService.start();mPlayPauseButton.setText(R.string.pause);}}});mStopButton.setOnClickListener(new Button.OnClickListener() {public void onClick(View v) {// Perform action on clickif (mMusicPlayerService != null ) {mTextView.setVisibility(View.VISIBLE);mPlayPauseButton.setVisibility(View.INVISIBLE);mStopButton.setVisibility(View.INVISIBLE); mMusicPlayerService.stop();}}});IntentFilter filter = new IntentFilter();filter.addAction(MusicPlayerService.PLAYER_PREPARE_END);filter.addAction(MusicPlayerService.PLAY_COMPLETED);registerReceiver(mPlayerEvtReceiver, filter);}protected void onResume() {super.onResume();mCursor = mMusicInfoController.getAllSongs();ListAdapter adapter = new MusicListAdapter(this,yout.simple_expandable_list_item_2, mCursor, new String[]{}, new int[]{});setListAdapter(adapter);}protected void onListItemClick(ListView l, View v, int position, long id) {super.onListItemClick(l, v, position, id);if (mCursor == null ||mCursor.getCount() == 0) {return;}mCursor.moveToPosition(position);String url = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));mMusicPlayerService.setDataSource(url);mMusicPlayerService.start();}/********************************************************************/class MusicListAdapter extends SimpleCursorAdapter {public MusicListAdapter(Context context, int layout, Cursor c,String[] from, int[] to) { super(context, layout, c, from, to);}public void bindView(View view, Context context, Cursor cursor) {super.bindView(view, context, cursor);TextView titleView = (TextView) view.findViewById(android.R.id.text1);TextView artistView = (TextView) view.findViewById(android.R.id.text2);titleView.setText(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)));artistView.setText(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)));//int duration cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));}public static String makeTimeString(long milliSecs) {StringBuffer sb = new StringBuffer();long m = milliSecs / (60 * 1000);sb.append(m < 10 ? "0" + m : m);sb.append(":");long s = (milliSecs % (60 * 1000)) / 1000;sb.append(s < 10 ? "0" + s : s);return sb.toString();}MusicPlayerApp.java package com.yarin.android.MusicPlayer;import android.app.Application;public class MusicPlayerApp extends Application{private MusicInfoController mMusicInfoController = null;public void onCreate(){ super.onCreate();mMusicInfoController = MusicInfoController.getInstance(this); }public MusicInfoController getMusicInfoController(){return mMusicInfoController;}}MusicPlayerService.javapackage com.yarin.android.MusicPlayer;import java.io.IOException;import android.app.Service;import android.content.Intent;import android.media.MediaPlayer;import android.os.Binder;import android.os.IBinder;public class MusicPlayerService extends Service{private final IBinder mBinder = new LocalBinder();private MediaPlayer mMediaPlayer = null;public static final String PLAYER_PREPARE_END = "com.yarin.musicplayerservice.prepared";public static final String PLAY_COMPLETED = "com.yarin.musicplayerservice.playcompleted";MediaPlayer.OnCompletionListener mCompleteListener = new MediaPlayer.OnCompletionListener(){public void onCompletion(MediaPlayer mp){ broadcastEvent(PLAY_COMPLETED);}};MediaPlayer.OnPreparedListener mPrepareListener = new MediaPlayer.OnPreparedListener(){public void onPrepared(MediaPlayer mp){ broadcastEvent(PLAYER_PREPARE_END);}};private void broadcastEvent(String what){Intent i = new Intent(what); sendBroadcast(i);}public void onCreate(){super.onCreate();mMediaPlayer = new MediaPlayer(); mMediaPlayer.setOnPreparedListener(mPrepareListener);mMediaPlayer.setOnCompletionListener(mCompleteListener);}public class LocalBinder extends Binder{public MusicPlayerService getService(){return MusicPlayerService.this;public IBinder onBind(Intent intent){return mBinder;}public void setDataSource(String path){try{mMediaPlayer.reset();mMediaPlayer.setDataSource(path); mMediaPlayer.prepare();}catch (IOException e){return;}catch (IllegalArgumentException e){return;}}public void start(){mMediaPlayer.start();}public void stop(){mMediaPlayer.stop();}public void pause(){mMediaPlayer.pause();public boolean isPlaying(){return mMediaPlayer.isPlaying();}public int getDuration(){return mMediaPlayer.getDuration();}public int getPosition(){return mMediaPlayer.getCurrentPosition();}public long seek(long whereto){mMediaPlayer.seekTo((int) whereto);return whereto;}}。

Android Studio Service编程 音乐播放器

Android Studio Service编程 音乐播放器

广州xx 学院Android 程序设计 实验报告专业班级 计算机181 实验日期__ 2021.5.18_ _ 姓 名 xx 学 号201xx 实验名称 Service 编程 指导老师__ xx _(报告内容包括:实验目的、实验设备及器材、实验步骤、实验数据、图表及曲线处理、实验小结等)。

1. 实验目的(1) 了解如何创建服务;(2) 掌握服务的两种启动方式;(3) 掌握如何使用本地服务通信。

2. 实验要求(1) 使用服务通信,实现音乐播放器功能,实现音乐的播放、暂停、继续播放、退出。

3. 实验步骤(1)导入音乐文件和界面图片之后,开始创建布局,代码如下,效果图如图1-1所示。

<ImageViewandroid :id ="@+id/iv_music"android :layout_width ="240dp"android :layout_height ="240dp"android :layout_gravity ="center_horizontal" android :layout_margin ="15dp"android :src ="@drawable/music"/><SeekBarandroid :id ="@+id/sb"android :layout_width ="match_parent"android :layout_height ="wrap_content" /><RelativeLayoutandroid :layout_width ="match_parent"android :layout_height ="wrap_content"android:paddingLeft="8dp"android:paddingRight="8dp"><TextViewandroid:id="@+id/tv_progress"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="00:00" /><TextViewandroid:id="@+id/tv_total"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentRight="true"android:text="00:00" /></RelativeLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><Buttonandroid:id="@+id/btn_play"android:layout_width="0dp"android:layout_height="40dp"android:layout_margin="8dp"android:layout_weight="1"android:background="@drawable/btn_bg_selector"android:text="播放音乐" /><Buttonandroid:id="@+id/btn_pause"android:layout_width="0dp"android:layout_height="40dp"android:layout_margin="8dp"android:layout_weight="1"android:background="@drawable/btn_bg_selector"android:text="暂停播放" /><Buttonandroid:id="@+id/btn_continue_play"android:layout_width="0dp"android:layout_height="40dp"android:layout_margin="8dp"android:layout_weight="1"android:background="@drawable/btn_bg_selector"android:text="继续播放" /><Buttonandroid:id="@+id/btn_exit"android:layout_width="0dp"android:layout_height="40dp"android:layout_margin="8dp"android:layout_weight="1"android:background="@drawable/btn_bg_selector"android:text="退出" /></LinearLayout>图1-1 界面布局效果图(2)创建背景选择器btn_bg_selector.xml关键代码如下:<selector xmlns:android="/apk/res/android"><item android:state_pressed="true" ><shape android:shape="rectangle"><corners android:radius="3dp"/><solid android:color="#d4d4d4"/></shape></item><item android:state_pressed="false" ><shape android:shape="rectangle"><corners android:radius="3dp"/><solid android:color="#ffffff" /></shape></item></selector>(3)创建MusicService服务关键代码如下所示:public class MusicService extends Service {private MediaPlayer player;private Timer timer;public MusicService() {}@Overridepublic IBinder onBind(Intent intent) {return new MusicControl();}@Overridepublic void onCreate() {super.onCreate();player = new MediaPlayer();//创建音乐播放器对象}public void addTimer() { //添加计时器用于设置音乐播放器中的播放进度条if (timer == null) {timer = new Timer(); //创建计时器对象TimerTask task = new TimerTask() {@Overridepublic void run() {if (player == null) return;int duration = player.getDuration(); //获取歌曲总时长int currentPosition = player.getCurrentPosition();//获取播放进度Message msg = MainActivity.handler.obtainMessage();//创建消息对象//将音乐的总时长和播放进度封装至消息对象中Bundle bundle = new Bundle();bundle.putInt("duration", duration);bundle.putInt("currentPosition", currentPosition);msg.setData(bundle);//将消息发送到主线程的消息队列MainActivity.handler.sendMessage(msg);}};//开始计时任务后的5毫秒,第一次执行task任务,以后每500毫秒执行一次timer.schedule(task, 5, 500);}}class MusicControl extends Binder {public void play() {try {player.reset();//重置音乐播放器//加载多媒体文件player = MediaPlayer.create(getApplicationContext(),R.raw.music);player.start();//播放音乐addTimer(); //添加计时器} catch (Exception e) {e.printStackTrace();}}public void pausePlay() {player.pause(); //暂停播放音乐}public void continuePlay() {player.start(); //继续播放音乐}public void seekTo(int progress) {player.seekTo(progress);//设置音乐的播放位置}}@Overridepublic void onDestroy() {super.onDestroy();if (player == null) return;if (player.isPlaying()) player.stop();//停止播放音乐player.release(); //释放占用的资源player = null; //将player置为空}}(4)编写界面交互代码关键代码如下:public class MainActivity extends AppCompatActivity implementsView.OnClickListener{private static SeekBar sb;private static TextView tv_progress, tv_total;private ObjectAnimator animator;private MusicService.MusicControl musicControl;MyServiceConn conn;Intent intent;private boolean isUnbind = false;//记录服务是否被解绑@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.activity_main);init();}private void init() {tv_progress = (TextView) findViewById(_progress);tv_total = (TextView) findViewById(_total);sb = (SeekBar) findViewById(R.id.sb);findViewById(R.id.btn_play).setOnClickListener(this);findViewById(R.id.btn_pause).setOnClickListener(this);findViewById(R.id.btn_continue_play).setOnClickListener(this);findViewById(R.id.btn_exit).setOnClickListener(this);intent = new Intent(this, MusicService.class);//创建意图对象conn = new MyServiceConn();//创建服务连接对象bindService(intent, conn, BIND_AUTO_CREATE); //绑定服务//为滑动条添加事件监听sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {@Overridepublic void onProgressChanged(SeekBar seekBar, int progress, booleanfromUser) { //滑动条进度改变时,会调用此方法if (progress == seekBar.getMax()) { //当滑动条滑到末端时,结束动画animator.pause(); //停止播放动画}}@Overridepublic void onStartTrackingTouch(SeekBar seekBar) {//滑动条开始滑动时调用}@Overridepublic void onStopTrackingTouch(SeekBar seekBar) { //滑动条停止滑动时调用//根据拖动的进度改变音乐播放进度int progress = seekBar.getProgress();//获取seekBar的进度musicControl.seekTo(progress); //改变播放进度}});ImageView iv_music = (ImageView) findViewById(R.id.iv_music);animator = ObjectAnimator.ofFloat(iv_music, "rotation", 0f, 360.0f);animator.setDuration(10000); //动画旋转一周的时间为10秒animator.setInterpolator(new LinearInterpolator());animator.setRepeatCount(-1); //-1表示设置动画无限循环}4.运行结果开始播放如图4-1所示图4-15.实验小结通过此次实验,让我了解到了Android中的服务创建,比如下载文件、播放音乐等功能,其中让我学到了一个背景选择器,可以通过这个选择器动态呈现按钮的背景颜色。

Android简易音乐播放器实现代码

Android简易音乐播放器实现代码

Android简易⾳乐播放器实现代码本⽂实例为⼤家分享了Android⾳乐播放器的具体代码,供⼤家参考,具体内容如下1.播放项⽬内的⾳乐package com.thm.g150820_android26_playmusic;import Android.media.MediaPlayer;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.ImageButton;import android.widget.SeekBar;public class MainActivity extends AppCompatActivity {private MediaPlayer mediaPlayer;private SeekBar seekBar;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.activity_main);seekBar = (SeekBar) findViewById(R.id.seekBar);seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {@Overridepublic void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {}@Overridepublic void onStartTrackingTouch(SeekBar seekBar) {}@Overridepublic void onStopTrackingTouch(SeekBar seekBar) {//获取拖动结束之后的位置int progress = seekBar.getProgress();//跳转到某个位置播放mediaPlayer.seekTo(progress);}});}public void isPlayOrPause(View view){//把View强转为ImageButtonImageButton imageButton = (ImageButton) view;if(mediaPlayer==null) {//实例化MediaPlayermediaPlayer = MediaPlayer.create(this, R.raw.yao);//开始播放mediaPlayer.start();//图标修改为暂停的图标imageButton.setImageResource(android.R.drawable.ic_media_pause);//获取⾳乐的总时长int duration = mediaPlayer.getDuration();//设置进度条的最⼤值为⾳乐的总时长seekBar.setMax(duration);new MyThre().start();}//判断如果⾳乐在播放else if(mediaPlayer.isPlaying()){//就暂停⾳乐mediaPlayer.pause();//图标修改为播放的图标imageButton.setImageResource(android.R.drawable.ic_media_play);}else{mediaPlayer.start();//图标修改为暂停的图标imageButton.setImageResource(android.R.drawable.ic_media_pause);}}//写内部类class MyThre extends Thread{@Overridepublic void run() {super.run();while(seekBar.getProgress()<=seekBar.getMax()){//获取当前⾳乐播放的位置int currentPosition = mediaPlayer.getCurrentPosition();//让进度条动起来seekBar.setProgress(currentPosition);}}}}2.播放内存卡中的⾳乐package com.thm.g150820_android26_playmusic;import android.media.AudioManager;import android.media.MediaPlayer;import .Uri;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.ImageButton;import android.widget.SeekBar;import java.io.IOException;public class MainActivity extends AppCompatActivity {private MediaPlayer mediaPlayer;private SeekBar seekBar;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.activity_main);seekBar = (SeekBar) findViewById(R.id.seekBar);seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Overridepublic void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { }@Overridepublic void onStartTrackingTouch(SeekBar seekBar) {}@Overridepublic void onStopTrackingTouch(SeekBar seekBar) {//获取拖动结束之后的位置int progress = seekBar.getProgress();//跳转到某个位置播放mediaPlayer.seekTo(progress);}});}public void isPlayOrPause(View view){//把View强转为ImageButtonImageButton imageButton = (ImageButton) view;if(mediaPlayer==null) {//实例化MediaPlayer//播放应⽤内的⾳乐//mediaPlayer = MediaPlayer.create(this, R.raw.yao);//播放内存卡中的⾳乐mediaPlayer = new MediaPlayer();//设置类型mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);//设置⾳乐路径try {mediaPlayer.setDataSource(this, Uri.parse("storage/sdcard0/Music/a.mp3"));//播放之前准备⼀下mediaPlayer.prepare();} catch (IOException e) {e.printStackTrace();}//开始播放mediaPlayer.start();//图标修改为暂停的图标imageButton.setImageResource(android.R.drawable.ic_media_pause);//获取⾳乐的总时长int duration = mediaPlayer.getDuration();//设置进度条的最⼤值为⾳乐的总时长seekBar.setMax(duration);new MyThre().start();}//判断如果⾳乐在播放else if(mediaPlayer.isPlaying()){//就暂停⾳乐mediaPlayer.pause();//图标修改为播放的图标imageButton.setImageResource(android.R.drawable.ic_media_play);}else{mediaPlayer.start();//图标修改为暂停的图标imageButton.setImageResource(android.R.drawable.ic_media_pause);}}//写线程内部类class MyThre extends Thread{@Overridepublic void run() {super.run();while(seekBar.getProgress()<=seekBar.getMax()){//获取当前⾳乐播放的位置int currentPosition = mediaPlayer.getCurrentPosition();//让进度条动起来seekBar.setProgress(currentPosition);}}}}3.添加读取内存的权限更多关于播放器的内容请点击进⾏学习。

最全的Android开源音乐播放器源码汇总

最全的Android开源音乐播放器源码汇总

最全的Android开源音乐播放器源码汇总收集了很多音乐播放器类的Android项目源码,非常不错的开源项目,会让你事半功倍,希望大家补充。

谢谢!Android基于经纬度切歌的冲绳音乐播放器源码Android应用源码适合新手学习的本地音乐播放器Android应用源码网络本地音乐播放器工程源码Android应用源码仿手机QQ音乐播放器项目Android应用源码超级精致的本地音乐播放器Android应用源码教学自学用音乐播放器Android应用源码25国语言音乐播放器Android应用源码仿唱片机音乐播放器Android应用源码仿多米音乐播放器项目Android应用源码安卓win8风格音乐播放器Android应用源码仿酷狗音乐播放器本地版Android应用源码安卓奇葩音乐播放器项目Android应用源码魔音盒音乐播放器项目Android应用源码音乐实时跳动频谱显示Android应用源码强大的3D音乐播放器项目Android应用源码仿安卓QQ音乐播放器项目android应用源码先锋音乐快剪铃声剪辑项目Android和讯音乐播放器培训项目Android应用源码安卓乐迹音乐播放器项目Android应用源码带歌词与频谱SMplaye音乐播放器Android应用源码含歌词列表gif简单音乐播放器Android应用源码国外在线电台音乐播放器.rarAndroid例子源码音乐播放器aidl实现进程间的通讯Android 音乐播放器android开发源码分享之在线音乐播放器完整项目jamendo_android一个开源的Android在线音乐播放器实例。

Android 音乐播放器(晴天播放)Android优雅音乐源码Android MusicPlayer音乐播放器源码Android 简易音乐播放器源码GitHub开源项目之Jamendo音乐播放器Android音乐播放器歌词显示实例。

Android应用开发--MP3音乐播放器代码实现(一)

Android应用开发--MP3音乐播放器代码实现(一)

Android应⽤开发--MP3⾳乐播放器代码实现(⼀)需求1:将内存卡中的MP3⾳乐读取出来并显⽰到列表当中1. 从数据库中查询所有⾳乐数据,保存到List集合当中,List当中存放的是Mp3Info对象2. 迭代List集合,把每⼀个Mp3Info对象的所有属性,保存到Map对象当中3. 定义⼀个List集合,把Map对象添加到List集合当中4. 通过定义⼀个SimpleAdpter,调⽤setAdpter⽅法,将数据显⽰到列表当中[java]1. /**2. * ⽤于从数据库中查询歌曲的信息,保存在List当中3. *4. * @return5. */6. public List<Mp3Info> getMp3Infos() {7. Cursor cursor = getContentResolver().query(8. MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,9. MediaStore.Audio.Media.DEFAULT_SORT_ORDER);10. List<Mp3Info> mp3Infos = new ArrayList<Mp3Info>();11. for (int i = 0; i < cursor.getCount(); i++) {12. Mp3Info mp3Info = new Mp3Info();13. cursor.moveToNext();14. long id = cursor.getLong(cursor15. .getColumnIndex(MediaStore.Audio.Media._ID)); //⾳乐id16. String title = cursor.getString((cursor17. .getColumnIndex(MediaStore.Audio.Media.TITLE)));//⾳乐标题18. String artist = cursor.getString(cursor19. .getColumnIndex(MediaStore.Audio.Media.ARTIST));//艺术家20. long duration = cursor.getLong(cursor21. .getColumnIndex(MediaStore.Audio.Media.DURATION));//时长22. long size = cursor.getLong(cursor23. .getColumnIndex(MediaStore.Audio.Media.SIZE)); //⽂件⼤⼩24. String url = cursor.getString(cursor25. .getColumnIndex(MediaStore.Audio.Media.DATA)); //⽂件路径26. int isMusic = cursor.getInt(cursor27. .getColumnIndex(MediaStore.Audio.Media.IS_MUSIC));//是否为⾳乐28. if (isMusic != 0) { //只把⾳乐添加到集合当中29. mp3Info.setId(id);30. mp3Info.setTitle(title);31. mp3Info.setArtist(artist);32. mp3Info.setDuration(duration);33. mp3Info.setSize(size);34. mp3Info.setUrl(url);35. mp3Infos.add(mp3Info);36. }37. }38. return mp3Infos;39. }[java]1. /**2. * 填充列表3. * @param mp3Infos4. */5. public void setListAdpter(List<Mp3Info> mp3Infos) {6. List<HashMap<String, String>> mp3list = new ArrayList<HashMap<String, String>>();7. for (Iterator iterator = mp3Infos.iterator(); iterator.hasNext();) {8. Mp3Info mp3Info = (Mp3Info) iterator.next();9. HashMap<String, String> map = new HashMap<String, String>();10. map.put("title", mp3Info.getTitle());11. map.put("Artist", mp3Info.getArtist());12. map.put("duration", String.valueOf(mp3Info.getDuration()));13. map.put("size", String.valueOf(mp3Info.getSize()));14. map.put("url", mp3Info.getUrl());15. mp3list.add(map);16. }17. mAdapter = new SimpleAdapter(this, mp3list,18. yout.music_list_item_layout, new String[] { "title", "Artist", "duration" },19. new int[] { R.id.music_title, R.id.music_Artist, R.id.music_duration });20. mMusiclist.setAdapter(mAdapter);21. }实现效果如图:需求2:点击列表的每⼀项,启动⼀个服务来播放⾳乐1. 注册条⽬点击监听器OnItemClickListener2. 定义⼀个实现OnItemClickListener接⼝的内部类3. 定义⼀个继承Service的服务类PlayerServie1. 注册条⽬点击监听器OnItemClickListener[java]1. mMusiclist = (ListView) findViewById(R.id.music_list);2. mMusiclist.setOnItemClickListener(new MusicListItemClickListener());3. mp3Infos = getMp3Infos();4. setListAdpter(getMp3Infos());2. 定义⼀个实现OnItemClickListener接⼝的内部类[java]1. private class MusicListItemClickListener implements OnItemClickListener {2. @Override3. public void onItemClick(AdapterView<?> parent, View view, int position,4. long id) {5. if(mp3Infos != null) {6. Mp3Info mp3Info = mp3Infos.get(position);7. Log.d("mp3Info-->", mp3Info.toString());8. Intent intent = new Intent();9. intent.putExtra("url", mp3Info.getUrl());10. intent.putExtra("MSG", AppConstant.PlayerMsg.PLAY_MSG);11. intent.setClass(MainActivity.this, PlayerService.class);12. startService(intent); //启动服务13. }14. }15. }3. 定义⼀个继承Service的服务类PlayerServie(未完善的Service类)[java]1. package com.wwj.sb.service;2.3.4. import android.annotation.SuppressLint;5. import android.app.Service;6. import android.content.Intent;7. import android.media.MediaPlayer;8. import android.media.MediaPlayer.OnPreparedListener;9. import android.os.IBinder;10.11. import com.wwj.sb.domain.AppConstant;12.13. @SuppressLint("NewApi")14. public class PlayerService extends Service {15. private MediaPlayer mediaPlayer = new MediaPlayer(); //媒体播放器对象16. private String path; //⾳乐⽂件路径17. private boolean isPause; //暂停状态18.19. @Override20. public IBinder onBind(Intent arg0) {21. return null;22. }23.24. @Override25. public int onStartCommand(Intent intent, int flags, int startId) {26. if(mediaPlayer.isPlaying()) {27. stop();28. }29. path = intent.getStringExtra("url");30. int msg = intent.getIntExtra("MSG", 0);31. if(msg == AppConstant.PlayerMsg.PLAY_MSG) {32. play(0);33. } else if(msg == AppConstant.PlayerMsg.PAUSE_MSG) {34. pause();35. } else if(msg == AppConstant.PlayerMsg.STOP_MSG) {36. stop();37. }38. return super.onStartCommand(intent, flags, startId);39. }40.41.42. /**43. * 播放⾳乐44. * @param position45. */46. private void play(int position) {47. try {48. mediaPlayer.reset();//把各项参数恢复到初始状态49. mediaPlayer.setDataSource(path);50. mediaPlayer.prepare(); //进⾏缓冲51. mediaPlayer.setOnPreparedListener(new PreparedListener(position));//注册⼀个监听器52. }53. catch (Exception e) {54. e.printStackTrace();55. }56. }57.58. /**59. * 暂停⾳乐60. */61. private void pause() {62. if (mediaPlayer != null && mediaPlayer.isPlaying()) {63. mediaPlayer.pause();64. isPause = true;65. }66. }67.68. /**69. * 停⽌⾳乐70. */71. private void stop(){72. if(mediaPlayer != null) {73. mediaPlayer.stop();74. try {75. mediaPlayer.prepare(); // 在调⽤stop后如果需要再次通过start进⾏播放,需要之前调⽤prepare函数76. } catch (Exception e) {77. e.printStackTrace();78. }79. }80. }81.82.83. @Override84. public void onDestroy() {85. if(mediaPlayer != null){86. mediaPlayer.stop();87. mediaPlayer.release();88. }89. }90. /**91. *92. * 实现⼀个OnPrepareLister接⼝,当⾳乐准备好的时候开始播放93. *94. */95. private final class PreparedListener implements OnPreparedListener {96. private int positon;97.98. public PreparedListener(int positon) {99. this.positon = positon;100. }101.102. @Override103. public void onPrepared(MediaPlayer mp) {104. mediaPlayer.start(); //开始播放105. if(positon > 0) { //如果⾳乐不是从头播放106. mediaPlayer.seekTo(positon);107. }108. }109. }110.111. }public class MusicActivity extends Activity {private boolean isStop = false;private MediaPlayer mPlayer;public final String TITLE = Environment.getExternalStorageDirectory()+ "/iwantyourlove.mp3";private File file;private SeekBar seekBar;private ImageView play;private TextView title;protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.music_main);initWidgets();}// 重新初始化播放器public void initWidgets() {play = (ImageView) findViewById(R.id.img_stop);title = (TextView) findViewById(R.id.title);seekBar = (SeekBar) findViewById(R.id.seek);seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Overridepublic void onStopTrackingTouch(SeekBar seekBar) {//seekBar.setProgress(mPlayer.getCurrentPosition() *seekBar.getMax() / total); //Log.i("sss", seekBar.getProgress()+"");//mPlayer.seekTo(mPlayer.getCurrentPosition());mPlayer.seekTo(seekBar.getProgress() * mPlayer.getDuration() /100 );}@Overridepublic void onStartTrackingTouch(SeekBar seekBar) {}@Overridepublic void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {// Log.i("progress", ""+progress);// Log.i("qqq", seekBar.getProgress()+"");// progress = currentPosition * 100 / duration;//progress*duration/100//mPlayer.seekTo(progress * mPlayer.getDuration() /100 );}});file = new File(TITLE);title.setText(file.getName());mPlayer = new MediaPlayer();try {mPlayer.setDataSource(TITLE);mPlayer.prepare();} catch (Exception e) {e.printStackTrace();}}public void play(View v) {if (!mPlayer.isPlaying()) {mPlayer.start();}}public void pause(View v) {if (mPlayer.isPlaying()) {mPlayer.pause();}}public void replay(View v) {mPlayer.reset();initWidgets();// 重新构建播放器// mPlayer.start();play(v);}public void stop(View v) {isStop = true;mPlayer.stop();play.setImageResource(R.drawable.player_play);}// ⽤图⽚代替按钮public void playOrPause(View v) {if (isStop) {// 停⽌后重新开始播放mPlayer.reset();initWidgets();mPlayer.start();play.setImageResource(R.drawable.player_pause);isStop = false;} else if (mPlayer.isPlaying()) {// 播放状态play.setImageResource(R.drawable.player_play);mPlayer.pause();} else {// 暂停状态play.setImageResource(R.drawable.player_pause);mPlayer.start();}// 异步任务new MusicTask().execute();}@Overrideprotected void onDestroy() {super.onDestroy();// 释放资源mPlayer.release();}// ⾳乐播放异步任务class MusicTask extends AsyncTask<Void, Void, Void> {//int current = mPlayer.getCurrentPosition();// 当前播放是什么位置,int total = mPlayer.getDuration(); // ⾳乐总共多长时间@Overrideprotected Void doInBackground(Void... params) {// 让SeekBar跟着⾳乐⼀起向右边⾛while (mPlayer.getCurrentPosition() <= total&&!isStop) { //!isPause不是停⽌状态try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}publishProgress();}return null;}@Overrideprotected void onProgressUpdate(Void... values) {super.onProgressUpdate(values);// Log.i("msg", ""+mPlayer.getCurrentPosition() * 100 / total);seekBar.setProgress(mPlayer.getCurrentPosition() *seekBar.getMax() / total); }@Overrideprotected void onPostExecute(Void result) {super.onPostExecute(result);}}}。

安卓音乐播放器实现代码

安卓音乐播放器实现代码

1. Mp3Player.java 文件package com.jacky.multimedia;import java.io.File;import java.io.FilenameFilter;import java.io.IOException;import java.util.ArrayList;import java.util.List;import android.app.ListActivity;import android.media.MediaPlayer;import android.media.MediaPlayer.OnCompletionListener;import android.os.Bundle;import android.os.Handler;import android.view.KeyEvent;import android.view.View;import android.widget.ArrayAdapter;import android.widget.ImageButton;import android.widget.ListView;import android.widget.SeekBar;import android.widget.SeekBar.OnSeekBarChangeListener;import android.widget.TextView;public class Mp3Player extends ListActivity {/** Called when the activity is first created. *//* 定义5个图像按钮*/private ImageButton mFrontImageButton = null;private ImageButton mStartImageButton = null;private ImageButton mPauseImageButton = null;private ImageButton mStopImageButton = null;private ImageButton mNextImageButton = null;/*定义进度handler,显示百分比进度*/Handler mPercentHandler = new Handler();/*定义拖动条*/private SeekBar mSeekBar=null;/*定义显示文本框*/private TextView curProgressText=null;private TextView curtimeAndTotaltime=null;/* 定于一个多媒体对象*/public MediaPlayer mMediaPlayer = null;/*定于一个数据播放列表,用来存放从指定文件中搜索到的文件*/private List<String> mMusicList = new ArrayList<String>();/* 定义在播放列表中的当前选择项*/private int currentListItme = 0;/*定义要播放的文件夹路径*/private static final String MUSIC_PATH = new String("/mnt/sdcard/");/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(yout.main);/* 更新播放列表*/musicList();/*初始化多媒体对象*/mMediaPlayer = new MediaPlayer();/*初始化图像按钮*/mFrontImageButton = (ImageButton) findViewById(stImageButton); mStopImageButton = (ImageButton) findViewById(R.id.StopImageButton); mStartImageButton = (ImageButton) findViewById(R.id.StartImageButton); mPauseImageButton = (ImageButton) findViewById(R.id.PauseImageButton); mNextImageButton = (ImageButton) findViewById(R.id.NextImageButton);/*初始化拖动条和当前进度显示值*/mSeekBar=(SeekBar)findViewById(R.id.SeekBar01);curProgressText=(TextView)findViewById(R.id.currentProgress); curtimeAndTotaltime=(TextView)findViewById(R.id.curtimeandtotaltime);/*监听停止按钮*/mStopImageButton.setOnClickListener(new ImageButton.OnClickListener() {@Overridepublic void onClick(View v){/*判断是否正在播放歌曲*/if (mMediaPlayer.isPlaying()){/*如果在播放歌曲时,按下开始按钮,则重开开始播放*/mMediaPlayer.reset();}}});/*监听开始按钮*/mStartImageButton.setOnClickListener(new ImageButton.OnClickListener(){@Overridepublic void onClick(View v){ /*播放当前选择歌曲,通过listView列表中onListItemClick方法得到选择的时第几项*/playMusic(MUSIC_PATH + mMusicList.get(currentListItme));/*开始播放歌曲时,同步进行更新拖动条进度*/startSeekBarUpdate();}});/*监听暂停按钮*/mPauseImageButton.setOnClickListener(new ImageButton.OnClickListener(){public void onClick(View view){if (mMediaPlayer.isPlaying()){/*如果有播放歌曲,暂停*/mMediaPlayer.pause();}else{/*如果没有播放歌曲,则开始播放*/mMediaPlayer.start();}}});/*监听下一首按钮*/mNextImageButton.setOnClickListener(new ImageButton.OnClickListener(){@Overridepublic void onClick(View arg0){nextMusic();}/*监听上一首按钮*/mFrontImageButton.setOnClickListener(new ImageButton.OnClickListener() {@Overridepublic void onClick(View arg0){FrontMusic();}});/*监听拖动条*/mSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {// TODO Auto-generated method stub/*如果拖动进度发生改变,则显示当前进度值*/curProgressText.setText("当前进度: "+progress);}@Overridepublic void onStartTrackingTouch(SeekBar seekBar) {// TODO Auto-generated method stubcurProgressText.setText("拖动中...");}@Overridepublic void onStopTrackingTouch(SeekBar seekBar) {// TODO Auto-generated method stubint dest = seekBar.getProgress();int mMax = mMediaPlayer.getDuration();int sMax = mSeekBar.getMax();mMediaPlayer.seekTo(mMax*dest/sMax);}});}/*按键处理时间,当按下返回按键时的处理方法*/public boolean onKeyDown(int keyCode, KeyEvent event){if ( keyCode == KeyEvent.KEYCODE_BACK){mMediaPlayer.stop();mMediaPlayer.release();this.finish();return true;}return super.onKeyDown(keyCode, event);}/*ListView选择项监听方法,即当前鼠标在列表中选择的第几项*/protected void onListItemClick(ListView l, View v, int position, long id){currentListItme = position;playMusic(MUSIC_PATH + mMusicList.get(position));}/*更新播放列表*/public void musicList(){/*从指定的路径中读取文件,并与播放列表关联*/File home = new File(MUSIC_PATH);/*读取指定类型的文件,在本程序,指定播放类型为mp3*/if (home.listFiles(new MusicFilter()).length > 0){/*读取文件*/for (File file : home.listFiles(new MusicFilter())){mMusicList.add(file.getName());}/*播放文件与播放列表关联*/ArrayAdapter<String> musicList = new ArrayAdapter<String>(Mp3Player.this,yout.musicitme, mMusicList); setListAdapter(musicList);}}/*播放指定路径中的音乐*/private void playMusic(String path){{/* 重置多媒体*/mMediaPlayer.reset();/*读取mp3文件*/mMediaPlayer.setDataSource(path);/*准备播放*/mMediaPlayer.prepare();/*开始播放*/mMediaPlayer.start();/*监听播放是否完成*/mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {public void onCompletion(MediaPlayer arg0){/*播放完当前歌曲,自动播放下一首*/nextMusic();}});}catch (IOException e){}}/*播放下一首*/private void nextMusic(){if (++currentListItme >= mMusicList.size()){currentListItme = 0;}else{playMusic(MUSIC_PATH + mMusicList.get(currentListItme));}}/*播放上一首歌曲*/private void FrontMusic(){if (--currentListItme >= 0){currentListItme = 0;}{playMusic(MUSIC_PATH + mMusicList.get(currentListItme));}}/*更新拖动条进度*/public void startSeekBarUpdate(){mPercentHandler.post(start);}Runnable start=new Runnable(){@Overridepublic void run() {// TODO Auto-generated method stubmPercentHandler.post(updatesb);//用一个handler更新SeekBar}};Runnable updatesb =new Runnable(){@Overridepublic void run() {// TODO Auto-generated method stubint position = mMediaPlayer.getCurrentPosition();int mMax = mMediaPlayer.getDuration();int sMax = mSeekBar.getMax();mSeekBar.setProgress(position*sMax/mMax);curtimeAndTotaltime.setT ext("当前播放时间:"+position/1000+"秒"+"\n歌曲总时间: "+mMax/1000+"秒");mPercentHandler.postDelayed(updatesb, 1000);//每秒钟更新一次}};}/*播放文件选择类*/class MusicFilter implements FilenameFilter{public boolean accept(File dir, String name){/*指定扩展名类型*/return (name.endsWith(".mp3"));}}2.main.xls文件<?xml version="1.0" encoding="utf-8"?><AbsoluteLayoutxmlns:android="/apk/res/android" android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"><ListViewandroid:id="@id/android:list"android:layout_width="fill_parent"android:layout_height="fill_parent"android:layout_weight="1"android:drawSelectorOnT op="false"/><ImageButtonandroid:id="@+id/LastImageButton"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_x="10px"android:layout_y="70px"android:src="@drawable/last"/><ImageButtonandroid:id="@+id/StopImageButton"android:layout_height="wrap_content"android:layout_width="wrap_content"android:layout_x="70px"android:layout_y="70px"android:src="@drawable/stop"/><ImageButtonandroid:id="@+id/StartImageButton"android:layout_height="wrap_content"android:layout_width="wrap_content"android:layout_x="130px"android:layout_y="70px"android:src="@drawable/start"/><ImageButtonandroid:id="@+id/PauseImageButton"android:layout_height="wrap_content"android:layout_width="wrap_content"android:layout_x="190px"android:layout_y="70px"android:src="@drawable/pause"/><ImageButtonandroid:id="@+id/NextImageButton"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_x="250px"android:layout_y="70px"android:src="@drawable/next"/><SeekBar android:id="@+id/SeekBar01"android:layout_height="wrap_content"android:layout_x="0dp"android:layout_y="200dp"android:layout_width="fill_parent"android:max="100"android:progress="0"android:secondaryProgress="50"android:visibility="visible"></SeekBar><TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_y="250dp" android:id="@+id/currentProgress"></TextView><TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_y="300dp" android:id="@+id/curtimeandtotaltime"></TextView></AbsoluteLayout>3.musictime.xls<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="/apk/res/android" android:id="@+id/T extView01"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="@string/hello"/>4.AndroidManifest.xls<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="/apk/res/android" package="com.jacky.multimedia"android:versionCode="1"android:versionName="1.0"><application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Mp3Player"android:label="@string/app_name"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="UNCHER" /></intent-filter></activity></application><uses-sdk android:minSdkVersion="3" /></manifest>。

Android手机平台音乐播放器策划方案和源代码

Android手机平台音乐播放器策划方案和源代码

目录第一章引言................................................................................................... - 1 -1.1 项目背景............................................................................................ - 1 -1.2 编写目的............................................................................................ - 2 -1.3 参考资料............................................................... 错误!未定义书签。

第二章系统需求分析..................................................................................... - 3 -2.1 功能需求(用例图分析)................................................................ - 3 -2.1.1 播放器的基本控制需求......................................................... - 3 -2.1.2 播放清单列表管理需求......................................................... - 5 -2.1.3 播放友好性需求..................................................................... - 7 -2.1.4 播放器扩展卡需求................................................................. - 8 -2.1.5 功能需求(时序图)分析.......................................................... - 9 -2.2 系统结构图和流程图...................................................................... - 10 -2.3 系统界面需求.................................................................................. - 11 -2.4 系统性能需求.................................................................................. - 12 -2.5 运行环境需求.................................................................................. - 12 - 第三章Android数据库设计 ........................................................................ - 13 -3.1 数据库及字段属性设计.................................................................. - 13 -3.1.1 字段设计(表、图)........................................................... - 13 -3.1.2 音乐播放器E-R图 .............................................................. - 15 -3.2 数据库连接...................................................................................... - 15 -3.2.1 创建数据库........................................................................... - 15 -3.2.2 操作数据库........................................................................... - 16 -3.2.3 数据显示............................................................................... - 17 - 第四章Android项目介绍 ............................................................................ - 18 -4.1 什么是Android? ........................................................................... - 18 -4.1.1 Android简介 ......................................................................... - 18 -4.1.2 Android Features特性........................................................... - 18 -4.1.3 Android基本框架(Android Architecture) ....................... - 19 -4.2 搭建Android开发环境 .................................................................. - 23 -4.3 Android常用工具的使用 ................................................................ - 25 -4.3.1 命令行的使用....................................................................... - 25 -4.3.2 Dalvik Debug Monitor Service (DDMS)的使用................... - 26 -4.4 Android 音乐播放器的工程 ........................................................... - 26 -4.4.1 Android项目 ......................................................................... - 26 -4.4.2 Android工程程序结构 ......................................................... - 27 -4.4.3 AndroidManifest.xml文件.................................................... - 29 - 第五章播放器系统功能详细设计............................................................... - 31 -5.1音乐播放器主界面功能实现........................................................... - 31 -5.1.1 播放器主界面....................................................................... - 31 -5.1.2 播放界面音轨的实现........................................................... - 32 -5.1.3 播放器播放、暂停、停止等功能....................................... - 35 -5.2 播放列表功能.................................................................................. - 36 -5.3 菜单功能.......................................................................................... - 38 -5.3.1 菜单界面............................................................................... - 38 -5.3.2 菜单功能实现....................................................................... - 39 -5.4 播放设置界面.................................................................................. - 41 -5.4.1 界面实现............................................................................... - 41 -5.4.2 歌词显示实现....................................................................... - 42 -5.5 手机扩展卡的访问.......................................................................... - 44 -5.5.1 文件浏览器界面................................................................... - 45 -5.5.2 文件浏览器功能实现........................................................... - 46 -5.6 数据存储方式.................................................................................. - 47 -5.6.1 SharedPreferences .................................................................. - 47 -5.6.2 File存储方式 ........................................................................ - 48 -5.6.3 SQLiteDatabase数据库 ........................................................ - 48 - 第六章结论...................................................................... 错误!未定义书签。

黑马程序员安卓教程:音乐播放器之编写框架

黑马程序员安卓教程:音乐播放器之编写框架

黑马程序员安卓教程:音乐播放器之编写框架我们已了解Service的原理和使用方法,下面就通过一个综合的案例来进一步掌握Service在项目中的编写方法。

设计需求:编写一个音乐播放器项目,实现功能:列表展示待播放的音乐,当点击列表中的某一条音乐时则后台开启一个服务用来播放该音乐。

具体实现步骤如下:1.新建工程【File】→【new】→【Android Application Project】命名为:03_百度音乐盒2.编写布局文件根据需求编写布局,效果如图1-1所示:图1-1所示图1-1对应的xml布局代码如例1-1:3.查找控件在主Activity中,根据控件的ID查找相关控件,代码如例1-2:4.编写实体bean新建一个包(com.itheima.baidubox.domain),在该包下新建一实体bean,用来封装每一首音乐信息。

代码如例1-3:例1-3例1-3是一个实体类,我们定义了该实体的name属性和path属性,并重写了其get方法和set方法。

同时,还在重写了该类的构造方法(无参构造方法和有参构造方法)。

5.编写适配器ListView 要展示待播放的音乐,我们需要调用ListView的setAdapter方法将待播放音乐部署到该ListView中。

具体步骤如下:模拟ListView数据源,代码如例1-4例1-4中new一个List 集合,然后向该集合中添加多个MusicInfo实体对象。

至此,数据源List集合已经编写完成,接下来就是编写适配器。

本例中,我们通过继承BaseAdapter来编写自己的适配器MyAdapter。

代码如例1-5所示:例1-5例1-5中MyAdapter继承BaseAdapter,并重写了getCount方法和getView方法,getCount方法返回了ListView列表中条目的数据,本例中就是数据源List集合的大小;getView方法返回了每一个条目的显示内容,本例new一个TextView用来展示待播放音乐的名称。

音乐播放器源代码

音乐播放器源代码

P align=center><TABLE borderColor=#4f3256 align=centerbackground=/zh_cn/home4u/sucai/gifanimation/line/0022.gifborder=1><TBODY><TR><TD style="FILTER: alpha(opacity=100,style=3)"> <P align=center><EMBED src=width=369 height=39type=audio/mpeg loop="-1" autostart="ture"volume="0"></P></TD></TR></TBODY></TABLE></P>autostart="true"中true或1表示自动播放,false或0表示手动播放loop="true" 中的true或1表示重复播放,false或0表示只播放一次width= height= 中的数字分别表示播放器的宽度和高度=0表示隐藏播放器EnableContextMenu="0" 禁右键ShowStatusBar="1" (带显示文件播放信息)=======================================================隐藏(hidden=true)播放器(不循环)<EMBED src=音乐网址hidden=true type=audio/x-ms-wma AUTOSTART="1">-----------------------------------------------------------隐藏(hidden=true)播放器(循环)<EMBED src=音乐网址hidden=true type=audio/mpeg AUTOSTART="1" loop="-1"> ---------------------------------------------------------------黑色[style="FILTER: xray()"]循环[loop="-1"]播放器<EMBED style="FILTER: xray()" src=音乐网址width=360 height=30type=audio/mpeg volume="0" autostart="true" loop="-1">--------------------------------------------------------------------------------浅兰色循环(loop="-1")播放器<EMBED src=音乐网址width=300 height=45 type=audio/mpeg loop="-1"autostart="true" volume="0">--------------------------------------------------------------------------掩饰自动播放器<TABLE style="FILTER: Alpha(Opacity=100, FinishOpacity=0, Style=2, StartX=20, StartY=40, FinishX=0, FinishY=0)gray(); WIDTH: 200px; HEIGHT: 83px"><TBODY><TR><TD><EMBED src=音乐网址width=200 height=40 type=audio/mpeg panel="0" autostart="true" loop="true"></TD></TR></TBODY></TABLE>-------------------------------------连播放时选择曲目的播放器<EMBEDpluginspage=/windows/mediaplayer/download/default.as p width=400 height=172 type=application/x-mplay er2 FileName="音乐网址" SHOWCONTROLS="1" SHOWSTATUSBAR="1" SHOWDISPLAY="1" SHOWGOTOBAR="1" AUTOSTART="true" PlayCount="1">----------------------------------------------------------------------------------------------显示曲名的黑色带彩自动播放器<EMBED style="FILTER: invert()" src=音乐网址width=320 height=45type=audio/x-ms-wma ShowStatusBar="1" loop="true" autostart="true">-------------------------------------------------------------------------显示曲名的灰白色面板<EMBED style="FILTER: Gray()" src="链接地址" width=300 height=69type=application/x-mplayer2 loop="-1" showcontrols="1" ShowDisplay="0" ShowStatusBar="1" autostart="1"></EMBED>------------------------------------------灰白面板<embed style="FILTER: Gray()" src=链接地址width=300 height=45 loop="-1" autostart="true"></EMBED>---------------------------------------------------------------(带显示文件播放信息)<EMBED src="链接地址" width=300 height=69 type=application/x-mplay er2loop="-1" showcontrols="1" ShowDisplay="0" ShowStatusBar="1"autostart="1"></EMBED>-----------------------------------------------黑色带彩棕色面板<EMBED style="FILTER: invert()" src=链接地址width=300 height=45 loop="-1" autostart="true"></EMBED>---------------------------------------------------------------------浅紫播放器<TABLE borderColor=#4F3256background=/DownloadImg/2010/09/0718/5119955_3.jpg border=1><TBODY><TR><TD style="FILTER: alpha(opacity=50,style=3)"><P align=center><EMBED src=音乐网址width=300 height=25 type=audio/mpeg loop="-1" autostart="false" volume="0"></P></TD></TR></TBODY></TABLE>----------------------------------------------------------------------------------------------粉色<TABLE borderColor=navybackground=/UploadFile/2005-9/200592522275884778.jpg border=0><TBODY><TR><TD style="FILTER: alpha(opacity=50,style=3)"><P align=center><EMBED src=音乐网址width=300 height=45 type=audio/mpeg loop="-1" autostart="0" volume="0"></P></TD></TR></TBODY></TABLE>------------------------------------------------------------------------------------黄色闪光<TABLE style="BORDER-RIGHT: #000000 3px dashed; BORDER-TOP: #000000 3px dashed; BORDER-LEFT: #000000 3px dashed; BORDER-BOTTOM: #000000 3px dashed" cellSpacing=0 cellPadding=0 bgColor=#00000><TBODY><TR><TD><TABLE borderColor=navybackground=/s-helpSite/domName/nxm/20041114123131568.gi f border=0><TBODY><TR><TD style="FILTER: alpha(opacity=50,style=3)"><P align=center><EMBED src=音乐网址width=400 height=35 type=audio/mpeg loop="-1" autostart="0" loop="-1"></P></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE>--------------------------------------------------------------------------------蓝色闪光<TABLE borderColor=#dee4fe cellSpacing=3 cellPadding=0background=/UploadFile/2004-12/2004123023101352.gif border=2><TBODY><TR><TD><TABLE align=center border=0><TBODY><TR><TD style="FILTER: alpha(opacity=60,style=3)"><P align=center><EMBED style="FILTER: Gray" src=音乐网址width=400 height=35 type=audio/mpeg volume="0" autostart="false" loop="-1"></P></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE>-------------------------------------------------------------------------花边黑色<TABLE style="BORDER-RIGHT: #000000 3px dashed; BORDER-TOP: #000000 3px dashed; BORDER-LEFT: #000000 3px dashed; BORDER-BOTTOM: #000000 3px dashed" cellSpacing=0 cellPadding=0 bgColor=#00000><TBODY><TR><TD><TABLE borderColor=#000000 align=center border=1><TBODY><TR><TD><P align=center><EMBED style="FILTER: Xray" src=音乐网址width=400 height=35 type=audio/mpeg volume="0" autostart="false" loop="-0"></P></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE>-----------------------------------------------------------------------------------------------------粉色花边<TABLE style="BORDER-RIGHT: #ff69b4 3px dotted; BORDER-TOP: #ff69b4 3px dotted; BORDER-LEFT: #ff69b4 3px dotted; BORDER-BOTTOM: #ff69b4 3px dotted" cellSpacing=0 cellPadding=0 align=center bgColor=white><TBODY><TR><TD><TABLE borderColor=#ff69b4 align=center bgColor=#ffccf5 border=2><TBODY><TR><TD style="FILTER: alpha(opacity=100,style=3)"><P align=center><EMBED src=音乐网址width=300 height=25 type=audio/mpeg volume="0" autostart="false" loop="-0"></P></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE>-------------------------------------------------------------------------------------------禁右键播放器<EMBED style="BORDER-RIGHT: silver 1px solid; BORDER-TOP: silver 1px solid; BORDER-LEFT: silver 1px solid; BORDER-BOTTOM: silver 1px solid" src=音乐网址width=200 height=40 type=audio/x-mplayer2 console="video" showstatusbar="0" EnableContextMenu="0" volume="0" autostart="0" loop="-1">---------------------------------------------------------------------------------上下移动<MARQUEE style="LEFT: 230px; ; TOP: 300px" scrollAmount=1 scrollDelay=200 direction=up behavior=alternate width=300 height=400><br><MARQUEE scrollAmount=1 scrollDelay=100 behavior=alternate><br><TABLE style="FILTER: progid:DXImageTransform.Microsoft.Shadow(color:#7ec0ee ,direction:145,strengt h:20)" cellSpacing=0 cellPadding=0 border=1><br><TBODY><br><TR><br><TD><EMBED style="FILTER: gray()" src=音乐网址width=200 height=20type=audio/mpeg showstatusbar="1" volume="0" loop="-1" autostart="1"></TD></TR></TBODY></TABLE></MARQUEE></MARQUEE>-------------------------------------------------------------------(显示文件标签信息)蓝色<DIV><EMBED src="链接地址" loop="-1" width=300 height=140 balance="true" showpositioncontrols="true" showtracker="true" showaudiocontrols="true" showcontrols="true" showstatusbar="true" showdisplay="true" displaysize="0" volume="100" autosize="true" autostart="true" animationatstart="true" transparentatstart="true"></EMBED></div>--------------------------------------------------(显示文件标签信息)灰白<DIV><EMBED style="FILTER: Gray()" src="链接地址" loop="-1" width=300height=140 balance="true" showpositioncontrols="true" showtracker="true" showaudiocontrols="true" showcontrols="true" showstatusbar="true" showdisplay="true" displaysize="0" volume="100" autosize="true"autostart="true" animationatstart="true"transparentatstart="true"></EMBED></div>----------------------------------------------------(显示文件标签信息)黑彩<DIV><EMBED style="FILTER: invert()" src="链接地址" loop="-1" width=300 height=140 balance="true" showpositioncontrols="true" showtracker="true"showaudiocontrols="true" showcontrols="true" showstatusbar="true" showdisplay="true" displaysize="0" volume="100" autosize="true"autostart="true" animationatstart="true"transparentatstart="true"></EMBED></div>-----------------------------------------------------------(显示文件标签信息)黑<DIV><EMBED style="FILTER: xray()" src="链接地址" loop="-1" width=300height=140 balance="true" showpositioncontrols="true" showtracker="true" showaudiocontrols="true" showcontrols="true" showstatusbar="true" showdisplay="true" displaysize="0" volume="100" autosize="true"autostart="true" animationatstart="true"transparentatstart="true"></EMBED></div>===================================================连放<EMBED style="FILTER: Gray()" src=音乐网址width=500 height=35type=audio/x-ms-wma controls="StatusBar,TACCtrl,ControlPanel" border="0" autostart="1" playcount="0" showtracker="1" volume="0"></EMBED>=========================================================图片播放器!<TABLE style="FILTER: alpha(opacity=100 Style=0 FinishOpacity=100)" borderColor=#000000 height=249 cellSpacing=0 cellPadding=0 width=314 background=/DownloadImg/2010/09/0718/5119955_4.gif border=0><TBODY><TR><TD width=314 height=180 cellpadding="0" cellspacing="0"></TD></TR><TR><TD align=left><P align=center><EMBED style="FILTER: alpha(opacity=100 Style=3 FinishOpacity=0)black(); style: " src=音乐网址width=310 height=28 type=video/x-ms-asf loop="-1" autostart="1" volume="0"></P></TD></TR></TBODY></TABLE>=================================================以上效果分见如下::为免各效果同时播放,以下autostart=0autostart="true"中true或1表示自动播放,false或0表示手动播放loop="true" 中的true或1表示重复播放,false或0表示只播放一次width= height= 中的数字分别表示播放器的宽度和高度=0表示隐藏播放器EnableContextMenu="0" 禁右键ShowStatusBar="1" (带显示文件播放信息)=======================================================隐藏(hidden=true)播放器(不循环)src="/LIU/all_about_you.wma" hidden="true"type="audio/x-ms-wma" allowscriptaccess="never" autostart="0">-----------------------------------------------------------隐藏(hidden=true)播放器(循环)src="/LIU/all_about_you.wma" hidden="true"type="audio/mpeg" allowscriptaccess="never" autostart="0" loop="-1">---------------------------------------------------------------黑色[style="FILTER: xray()"]循环[loop="-1"]播放器style="FILTER: xray()" src="/LIU/all_about_you.wma" width="360" height="30" type="audio/mpeg" allowscriptaccess="never"volume="0" autostart="0" loop="-1">--------------------------------------------------------------------------------浅兰色循环(loop="-1")播放器src="/LIU/all_about_you.wma" width="300" heigh t="45" type="audio/mpeg" allowscriptaccess="never" loop="-1" autostart="0"volume="0">--------------------------------------------------------------------------掩饰自动播放器src="/LIU/all_about_you.wma"width="200" height="40" type="audio/mpeg"allowscriptaccess="never" panel="0" autostart="0"loop="true">-------------------------------------连播放时选择曲目的播放器pluginspage="/windows/mediaplayer/download/default.a sp" width="400" height="172" type="application/x-mplayer2"allowscriptaccess="never"filename="/LIU/all_about_you.wma" showcontrols="1" showstatusbar="1" showdisplay="1" showgotobar="1" autostart="0"playcount="1">----------------------------------------------------------------------------------------------显示曲名的黑色带彩自动播放器style="FILTER: invert()" src="/LIU/all_about_you.wma" width="320" height="45" type="audio/x-ms-wma" allowscriptaccess="never" showstatusbar="1" loop="0" autostart="0">-------------------------------------------------------------------------显示曲名的灰白色面板style="FILTER: Gray()" src="/LIU/all_about_you.wma" width="300" height="69" type="application/x-mplay er2" allowscriptaccess="never" loop="-1" showcontrols="1" showdisplay="0" showstatusbar="1" autostart="0"> ------------------------------------------灰白面板style="FILTER: Gray()" src="/LIU/all_about_you.wma" width="300" height="45" type="audio/x-ms-wma" allowscriptaccess="never"loop="-1" autostart="0">---------------------------------------------------------------(带显示文件播放信息)src="/LIU/all_about_you.wma" width="300" height="69" type="application/x-mplay er2" allowscriptaccess="never" loop="-1"showcontrols="1" showdisplay="0" showstatusbar="1" autostart="0">-----------------------------------------------黑色带彩棕色面板style="FILTER: invert()" src="/LIU/all_about_you.wma" width="300" height="45" type="audio/x-ms-wma" allowscriptaccess="never"loop="-1" autostart="0"><CENTER><TABLE style="BORDER-RIGHT: #f1dda1 2px ridge; BORDER-TOP: #bdb76b 2px ridge; BORDER-LEFT: #f1dda1 2px ridge; BORDER-BOTTOM: #bdb76b 2px ridge; BACKGROUND-COLOR: white" borderColor=#ffffff cellPadding=0width=300 align=centerbackground=/fileuploaddir/4B2686448.4.gifborder=0><TBODY><TR><TD width=300 height=20 cellPadding="0"cellSpacing="0"><TABLE align=center border=0><TBODY><TR><TDstyle="FILTER: alpha(opacity=60,style=3)"><P align=center><EMBED style="FILTER: invert(); WIDTH: 290px; HEIGHT: 28px" src=/Q/.Wma type=audio/x-ms-wma autostart="true"loop="-1"volume="0"></P></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE></CENTER一、音乐播放器源代码(神采飞扬版)P align=center><TABLE borderColor=#4f3256 align=center background=http://tech.china.com/zh_cn/home4u/sucai/gifanimation/line/0022.gif border=1><TBODY><TR><TD style="FILTER: alpha(opacity=100,style=3)"><P align=center><EMBED src=width=369 height=39type=audio/mpeg loop="-1" autostart="ture" volume="0"></P></TD></TR> </TBODY></TABLE></P>二、具体操作步骤1、在“BLOG发表文章”网页里,也即是写文章的网页里,写好文字后,选中文字上方的“查看HTML源代码”项(选项前的方框内出现√则为选中),这时我们看见原来的文字成了汉字、英文字母和一些诸如<、/、=等符号组成的乱码。

一个完整android音乐播放器源码

一个完整android音乐播放器源码

本文出自:欢迎转载,转载请注明出自:安卓开发网下面将和大家一起介绍一个音乐播放器项目,完成后的播放器具有暂停,下一首,前一首,歌曲列表,播放条进度等一些基本功能,它只是播放SDCARD上的.map文件,Android SDK为我们提供了一个MeidaPlayer类,有了这个类我们可以很方便的创建一个mdeiaplayer服务,该类中具有一些方法:MediaPlayer mp = new MediaPlayer();// 设置文件存储路径setDataSource("/sdcard/path_to_song");// 播放mp.start();// 暂短mp.pause();// 复位mp.reset();// 获取当前播放时长mp.getDuration();// 进度条mp.getCurrentDuration();// Move song to particular second - used for Forward or Backwardmp.seekTo(positon); // position in milliseconds// 检测歌曲是否正在播放mp.isPlaying(); // returns true or false1:音乐播放器的界面:播放器界面中所用的一些布局图片,这些图片大家可以到android SDK文件夹下或是到网络中去寻找一些类似就可以,并不一定要这些图片,代码才是我们的关键,3:然后我们需要写一个XML布局文件用于播放器的播按钮在不同状态下的图片,此XML文件保存在drawable文件夹下,btn_play.xml<selector xmlns:android=""><item android:drawable="@drawable/img_btn_play_pressed"android:state_focused="true"android:state_pressed="true" /><item android:drawable="@drawable/img_btn_play_pressed"android:state_focused="false"android:state_pressed="true" /><item android:drawable="@drawable/img_btn_play_pressed"android:state_focused="true" /><item android:drawable="@drawable/img_btn_play"android:state_focused="false"android:state_pressed="false" /></selector>提示:大家可以根据此XML文件完成其它的一些按钮布局文件,在这里就没有再为大家一一提供了,4:为了让播放器更绚,我们可以自定义一个SeekBar作为歌曲的播放进度,自定义风格代如下:(4.1)更换背景图片:seekbar_progress_bg.xml<?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android=""><item><clip><bitmap xmlns:android=""android:src="@drawable/img_seekbar_progress_blue"android:tileMode="repeat"android:antialias="true"android:dither="false"android:filter="false"android:gravity="left"/></clip></item>(4.2)Changing SeekBar Progress:seekbar_progress.xml<?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android=""><item android:id="@android:id/background"android:drawable="@drawable/img_seekbar_bg"android:dither="true"></item><item android:id="@android:id/secondaryProgress"><clip><shape><gradientandroid:startColor="#80028ac8"android:centerColor="#80127fb1"android:centerY="0.75"android:endColor="#a004638f"android:angle="270"/></shape></clip></item><itemandroid:id="@android:id/progress"android:drawable="@drawable/seekbar_progress_bg"/></layer-list>(4.3)实际的Seekbar控件定义如下:<SeekBarandroid:id="@+id/songProgressBar"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_marginRight="20dp"android:layout_marginLeft="20dp"android:layout_marginBottom="20dp"android:layout_above="@id/player_footer_bg"android:thumb="@drawable/seek_handler"android:progressDrawable="@drawable/seekbar_progress"android:paddingLeft="6dp"android:paddingRight="6dp"/>5:接下来我们将实现播放的整体界面的布局文件:player.xml<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android=""android:layout_width="match_parent"android:layout_height="match_parent"android:background="@color/player_background"><!-- Player Header --><LinearLayoutandroid:id="@+id/player_header_bg"android:layout_width="fill_parent"android:layout_height="60dip"android:background="@layout/bg_player_header"android:layout_alignParentTop="true"android:paddingLeft="5dp"android:paddingRight="5dp"><!-- Song Title --><TextViewandroid:id="@+id/songTitle"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:textColor="#04b3d2"android:textSize="16dp"android:paddingLeft="10dp"android:textStyle="bold"android:text="The Good, The Bad And The Ugly"android:layout_marginTop="10dp"/><!-- Playlist button --><ImageButtonandroid:id="@+id/btnPlaylist"android:layout_width="wrap_content"android:layout_height="fill_parent"android:src="@drawable/btn_playlist"android:background="@null"/></LinearLayout><!-- Song Thumbnail Image --><LinearLayoutandroid:id="@+id/songThumbnail"android:layout_width="fill_parent"android:layout_height="wrap_content"android:paddingTop="10dp"android:paddingBottom="10dp"android:gravity="center"android:layout_below="@id/player_header_bg"><ImageView android:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/adele"/></LinearLayout><!-- Player Footer --><LinearLayoutandroid:id="@+id/player_footer_bg"android:layout_width="fill_parent"android:layout_height="100dp"android:layout_alignParentBottom="true" android:background="@layout/bg_player_footer" android:gravity="center"><!-- Player Buttons --><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="horizontal"android:gravity="center_vertical"android:background="@layout/rounded_corner"android:paddingLeft="10dp"android:paddingRight="10dp"><!-- Previous Button --><ImageButtonandroid:id="@+id/btnPrevious"android:src="@drawable/btn_previous"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="@null"/><!-- Backward Button --><ImageButtonandroid:id="@+id/btnBackward"android:src="@drawable/btn_backward"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="@null"/><!-- Play Button --><ImageButtonandroid:id="@+id/btnPlay"android:src="@drawable/btn_play"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="@null"/><!-- Forward Button --><ImageButtonandroid:id="@+id/btnForward"android:src="@drawable/btn_forward"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="@null"/><!-- Next Button --><ImageButtonandroid:id="@+id/btnNext"android:src="@drawable/btn_next"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="@null"/></LinearLayout></LinearLayout><!-- Progress Bar/Seek bar --><SeekBarandroid:id="@+id/songProgressBar"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_marginRight="20dp"android:layout_marginLeft="20dp"android:layout_marginBottom="20dp"android:layout_above="@id/player_footer_bg"android:thumb="@drawable/seek_handler"android:progressDrawable="@drawable/seekbar_progress"android:paddingLeft="6dp"android:paddingRight="6dp"/><!-- Timer Display --><LinearLayoutandroid:id="@+id/timerDisplay"android:layout_above="@id/songProgressBar"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_marginRight="20dp"android:layout_marginLeft="20dp"android:layout_marginBottom="10dp"><!-- Current Duration Label --><TextViewandroid:id="@+id/songCurrentDurationLabel"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_weight="1"android:gravity="left"android:textColor="#eeeeee"android:textStyle="bold"/><!-- Total Duration Label --><TextViewandroid:id="@+id/songTotalDurationLabel"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_weight="1"android:gravity="right"android:textColor="#04cbde"android:textStyle="bold"/></LinearLayout><!-- Repeat / Shuffle buttons --><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_above="@id/timerDisplay"android:gravity="center"><!-- Repeat Button --><ImageButtonandroid:id="@+id/btnRepeat"android:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/btn_repeat"android:layout_marginRight="5dp"android:background="@null"/><!-- Shuffle Button --><ImageButtonandroid:id="@+id/btnShuffle"android:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/btn_shuffle"android:layout_marginLeft="5dp"android:background="@null"/></LinearLayout></RelativeLayout>6:有了播放器的播放界面后,我们再将所有歌曲显示的界面实现了,播放器的歌曲列表用的一个listview控件,同样我们也为该listview控件自定义,适合播放的整体界面风格,list_selector.xml<?xml version="1.0" encoding="utf-8"?><selector xmlns:android=""><!-- Selector style for listrow --><itemandroid:state_selected="false"android:state_pressed="false"android:drawable="@drawable/gradient_bg" /><item android:state_pressed="true"android:drawable="@drawable/gradient_bg_hover" /><item android:state_selected="true"android:state_pressed="false"android:drawable="@drawable/gradient_bg_hover" /></selector>歌曲列表界面布局文件:playlist.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android=""android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical"><ListViewandroid:id="@android:id/list"android:layout_width="fill_parent"android:layout_height="fill_parent"android:divider="#242424"android:dividerHeight="1dp"android:listSelector="@drawable/list_selector" /></LinearLayout>listviewr的item界面布局,用于定义单个歌曲的显示界面:playlist_item.xml<?xml version="1.0"encoding="utf-8"?><LinearLayout xmlns:android=""android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:gravity="center"android:background="@drawable/list_selector"android:padding="5dp"><TextViewandroid:id="@+id/songTitle"android:layout_width="fill_parent"android:layout_height="wrap_content"android:textSize="16dp"android:padding="10dp"android:color="#f3f3f3"/></LinearLayout>歌曲列表界面图:7:到此为止我们在上面已经完成了该项目的所有布局文件,下面我们就来实现SongManager.java类,这个类用于扫描设备中所有.mp3文件,SongsManager.mp3public class SongsManager {// SDCard Pathfinal String MEDIA_PATH = new String("/sdcard/");private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();// Constructorpublic SongsManager(){}/*** Function to read all mp3 files from sdcard* and store the details in ArrayList* */public ArrayList<HashMap<String, String>> getPlayList(){= new );if (home.listFiles(new ()).length > 0) {for ( : home.listFiles(new ())) {HashMap<String, String> song = new HashMap<String, String>();song.put("songTitle", ().substring(0, (().length() - 4)));song.put("songPath", ());// Adding each song to SongListsongsList.add(song);}}// return songs list arrayreturn songsList;}/*** Class to filter files which are having .mp3 extension* */class implements {public boolean accept(, String name) {return (name.endsWith(".mp3") || name.endsWith(".MP3"));}}}8:创建一个新的Activity 类,该类用于显示在ongsManager.java中扫描到的所有歌曲,PlayListActivity.javapackage com.androidhive.musicplayer;import java.util.ArrayList;import java.util.HashMap;import android.app.ListActivity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.ListAdapter;import android.widget.ListView;import android.widget.SimpleAdapter;public class PlayListActivity extends ListActivity {// Songs listpublic ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.playlist);ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();SongsManager plm = new SongsManager();// get all songs from sdcardthis.songsList = plm.getPlayList();// looping through playlistfor (int i = 0; i < songsList.size(); i++) {// creating new HashMapHashMap<String, String> song = songsList.get(i);// adding HashList to ArrayListsongsListData.add(song);}// Adding menuItems to ListViewListAdapter adapter = new SimpleAdapter(this, songsListData,yout.playlist_item, new String[] { "songTitle" }, new int[] {R.id.songTitle });setListAdapter(adapter);// selecting single ListView itemListView lv = getListView();// listening to single listitem clicklv.setOnItemClickListener(new OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view,int position, long id) {// getting listitem indexint songIndex = position;// Starting new intentIntent in = new Intent(getApplicationContext(),AndroidBuildingMusicPlayerActivity.class);// Sending songIndex to PlayerActivityin.putExtra("songIndex", songIndex);setResult(100, in);// Closing PlayListViewfinish();}});}}9:下面我们再来实现播放的主类AndroidBuildingMusicPlayerActivity.java:该类主要实现功能如下:1:在歌曲列表界面点击一首歌曲进入播放界面;2:播放,暂停,快进,复位等功能实现3:重复播放单一歌曲,随机播放等该类的完整代码如下:public class AndroidBuildingMusicPlayerActivity extends Activity implements OnCompletionListener, SeekBar.OnSeekBarChangeListener {private ImageButton btnPlay;private ImageButton btnForward;private ImageButton btnBackward;private ImageButton btnNext;private ImageButton btnPrevious;private ImageButton btnPlaylist;private ImageButton btnRepeat;private ImageButton btnShuffle;private SeekBar songProgressBar;private TextView songTitleLabel;private TextView songCurrentDurationLabel;private TextView songTotalDurationLabel;// Media Playerprivate MediaPlayer mp;// Handler to update UI timer, progress bar etc,.private Handler mHandler = new Handler();;private SongsManager songManager;private Utilities utils;private int seekForwardTime = 5000; // 5000 millisecondsprivate int seekBackwardTime = 5000; // 5000 millisecondsprivate int currentSongIndex = 0;private boolean isShuffle = false;private boolean isRepeat = false;private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.player);// 所有的播放按钮btnPlay = (ImageButton) findViewById(R.id.btnPlay);btnForward = (ImageButton)findViewById(R.id.btnForward);btnBackward = (ImageButton)findViewById(R.id.btnBackward);btnNext = (ImageButton) findViewById(R.id.btnNext);btnPrevious = (ImageButton)findViewById(R.id.btnPrevious);btnPlaylist = (ImageButton)findViewById(R.id.btnPlaylist);btnRepeat = (ImageButton)findViewById(R.id.btnRepeat);btnShuffle = (ImageButton)findViewById(R.id.btnShuffle);songProgressBar = (SeekBar)findViewById(R.id.songProgressBar);songTitleLabel = (TextView)findViewById(R.id.songTitle);songCurrentDurationLabel = (TextView)findViewById(R.id.songCurrentDurationLabel);songTotalDurationLabel = (TextView)findViewById(R.id.songTotalDurationLabel);// Mediaplayermp = new MediaPlayer();songManager = new SongsManager();utils = new Utilities();// ListenerssongProgressBar.setOnSeekBarChangeListener(this); // Importantmp.setOnCompletionListener(this); // Important// 获取所有歌曲列表songsList = songManager.getPlayList();// 默认从第一首开始播放playSong(0);/*** Play button click event* plays a song and changes button to pause image* pauses a song and changes button to play image* */btnPlay.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View arg0) {// check for already playingif(mp.isPlaying()){if(mp!=null){mp.pause();// Changing button image to play buttonbtnPlay.setImageResou rce(R.drawable.btn_play);}}else{// Resume songif(mp!=null){mp.start();// Changing button image to pause buttonbtnPlay.setImageResou rce(R.drawable.btn_pause);}}}});/*** Forward button click event* Forwards song specified seconds* */btnForward.setOnClickListener(newView.OnClickListener() {@Overridepublic void onClick(View arg0) {// get current song positionint currentPosition =mp.getCurrentPosition();// check if seekForward time is lesser than song durationif(currentPosition + seekForwardTime <= mp.getDuration()){// forward songmp.seekTo(currentPosition + seekForwardTime);}else{// forward to end positionmp.seekTo(mp.getDuration());}}});/*** Backward button click event* Backward song to specified seconds* */btnBackward.setOnClickListener(newView.OnClickListener() {@Overridepublic void onClick(View arg0) {// get current song positionint currentPosition =mp.getCurrentPosition();// check if seekBackward time is greater than 0 secif(currentPosition - seekBackwardTime >= 0){// forward songmp.seekTo(currentPosition - seekBackwardTime);}else{// backward to starting positionmp.seekTo(0);}}});/*** Next button click event*点击后一首歌事件* */btnNext.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View arg0) {// check if next song is there or notif(currentSongIndex < (songsList.size() - 1)){playSong(currentSongIndex + 1);currentSongIndex = currentSongIndex + 1;}else{// play first songplaySong(0);currentSongIndex = 0;}}});/*** 单击:前一首按钮事件* */btnPrevious.setOnClickListener(newView.OnClickListener() {@Overridepublic void onClick(View arg0) {if(currentSongIndex > 0){playSong(currentSongIndex - 1);currentSongIndex = currentSongIndex - 1;}else{// play last songplaySong(songsList.size() - 1);currentSongIndex = songsList.size() - 1;}}});/***循环播放按钮事件* */btnRepeat.setOnClickListener(newView.OnClickListener() {@Overridepublic void onClick(View arg0) {if(isRepeat){isRepeat = false;Toast.makeText(getApplication Context(), "Repeat is OFF", Toast.LENGTH_SHORT).show();btnRepeat.setImageResource(R. drawable.btn_repeat);}else{// make repeat to trueisRepeat = true;Toast.makeText(getApplication Context(), "Repeat is ON", Toast.LENGTH_SHORT).show();// make shuffle to falseisShuffle = false;btnRepeat.setImageResource(R. drawable.btn_repeat_focused);btnShuffle.setImageResource(R .drawable.btn_shuffle);}}});/*** 随机播放按钮事件* */btnShuffle.setOnClickListener(newView.OnClickListener() {@Overridepublic void onClick(View arg0) {if(isShuffle){isShuffle = false;Toast.makeText(getApplication Context(), "Shuffle is OFF", Toast.LENGTH_SHORT).show();btnShuffle.setImageResource(R .drawable.btn_shuffle);}else{// make repeat to trueisShuffle= true;Toast.makeText(getApplication Context(), "Shuffle is ON", Toast.LENGTH_SHORT).show();// make shuffle to falseisRepeat = false;btnShuffle.setImageResource(R .drawable.btn_shuffle_focused);btnRepeat.setImageResource(R. drawable.btn_repeat);}}});/*** Button Click event for Play list click event* Launches list activity which displays list of songs* */btnPlaylist.setOnClickListener(newView.OnClickListener() {@Overridepublic void onClick(View arg0) {Intent i = newIntent(getApplicationContext(), PlayListActivity.class);startActivityForResult(i, 100);}});}/*** Receiving song index from playlist view* and play the song* */@Overrideprotected void onActivityResult(int requestCode,int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);if(resultCode == 100){currentSongIndex =data.getExtras().getInt("songIndex");// play selected songplaySong(currentSongIndex);}}/*** Function to play a song* @param songIndex - index of song* */public void playSong(int songIndex){// Play songtry {mp.reset();mp.setDataSource(songsList.get(songIndex).get ("songPath"));mp.prepare();mp.start();// Displaying Song titleString songTitle =songsList.get(songIndex).get("songTitle");songTitleLabel.setText(songTitle);// Changing Button Image to pause imagebtnPlay.setImageResource(R.drawable.btn_pause );// set Progress bar valuessongProgressBar.setProgress(0);songProgressBar.setMax(100);// Updating progress barupdateProgressBar();} catch (IllegalArgumentException e) {e.printStackTrace();} catch (IllegalStateException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}/*** Update timer on seekbar* */public void updateProgressBar() {mHandler.postDelayed(mUpdateTimeTask, 100);}/*** Background Runnable thread* */private Runnable mUpdateTimeTask = new Runnable() {public void run() {long totalDuration = mp.getDuration();long currentDuration =mp.getCurrentPosition();// Displaying Total Duration timesongTotalDurationLabel.setText(""+utils .milliSecondsToTimer(totalDuration));// Displaying time completed playingsongCurrentDurationLabel.setText(""+uti liSecondsToTimer(currentDuration));// Updating progress barint progress =(int)(utils.getProgressPercentage(currentDuration, totalDuration));//Log.d("Progress", ""+progress);songProgressBar.setProgress(progress);// Running this thread after 100 millisecondsmHandler.postDelayed(this, 100);}};/**** */@Overridepublic void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {}/*** When user starts moving the progress handler* */@Overridepublic void onStartTrackingTouch(SeekBar seekBar) {// remove message Handler from updating progress barmHandler.removeCallbacks(mUpdateTimeTask);}/*** When user stops moving the progress hanlder* */@Overridepublic void onStopTrackingTouch(SeekBar seekBar) {mHandler.removeCallbacks(mUpdateTimeTask);int totalDuration = mp.getDuration();int currentPosition =utils.progressToTimer(seekBar.getProgress(), totalDuration);// forward or backward to certain secondsmp.seekTo(currentPosition);// update timer progress againupdateProgressBar();}/*** On Song Playing completed* if repeat is ON play same song again* if shuffle is ON play random song* */@Overridepublic void onCompletion(MediaPlayer arg0) {// check for repeat is ON or OFFif(isRepeat){// repeat is on play same song againplaySong(currentSongIndex);} else if(isShuffle){// shuffle is on - play a random songRandom rand = new Random();currentSongIndex =rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;playSong(currentSongIndex);} else{// no repeat or shuffle ON - play next songif(currentSongIndex < (songsList.size() - 1)){playSong(currentSongIndex + 1);currentSongIndex = currentSongIndex + 1;}else{// play first songplaySong(0);currentSongIndex = 0;}}}@Overridepublic void onDestroy(){super.onDestroy();mp.release();}}10:项目的功能配置文件AndroidManifest.xmlAndroidManifest.xml<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android=""package="com.androidhive.musicplayer"android:versionCode="1"android:versionName="1.0" ><uses-sdk android:minSdkVersion="8" /><applicationandroid:icon="@drawable/ic_launcher"android:label="@string/app_name" ><activityandroid:name=".AndroidBuildingMusicPlayerActivity"android:label="@string/app_name"android:configChanges="keyboardHidden|orientation"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="UNCHER" /> </intent-filter></activity><activityandroid:name=".PlayListActivity" /></application></manifest>。

android音乐播放器---源代码

android音乐播放器---源代码
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:background="@drawable/bg1">
<TextView android:layout_x="93px" android:layout_height="wrap_content"
<TextView android:layout_x="145px" android:layout_height="wrap_content"
android:text="" android:layout_y="65px" android:id="@+id/current_music"
android:textSize="18px" android:textColor="#C0FF3E"
<dimen name="button_size">40px</dimen>
</resources>
color.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="white">#ffffff</color>
android:layout_height="wrap_content" />

简单实现Android本地音乐播放器

简单实现Android本地音乐播放器

简单实现Android本地⾳乐播放器⾳乐播放需要调⽤service,在此,只是简单梳理播放流程。

public class PlayMusicService extends Service {//绑定服务调⽤服务的⽅法。

@Overridepublic IBinder onBind(Intent intent) {return null;}}<LinearLayout xmlns:android="/apk/res/android"xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity" ><EditTextandroid:id="@+id/et_path"android:layout_width="fill_parent"android:layout_height="wrap_content"android:hint="请输⼊要播放⽂件的路径" /><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal" ><Buttonandroid:id="@+id/bt_play"android:onClick="play"android:layout_width="0dip"android:layout_height="wrap_content"android:layout_weight="1"android:text="播放" /><Buttonandroid:id="@+id/bt_pause"android:onClick="pause"android:layout_width="0dip"android:layout_height="wrap_content"android:layout_weight="1"android:text="暂停" /><Buttonandroid:id="@+id/bt_stop"android:onClick="stop"android:layout_width="0dip"android:layout_height="wrap_content"android:layout_weight="1"android:text="停⽌" /><Buttonandroid:id="@+id/bt_replay"android:onClick="replay"android:layout_width="0dip"android:layout_height="wrap_content"android:layout_weight="1"android:text="重播" /></LinearLayout></LinearLayout>public class MainActivity extends Activity {private EditText et_path;private MediaPlayer mediaPlayer;private Button bt_play,bt_pause,bt_stop,bt_replay;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.activity_main);et_path = (EditText) findViewById(R.id.et_path);bt_play = (Button) findViewById(R.id.bt_play);bt_pause = (Button) findViewById(R.id.bt_pause);bt_stop = (Button) findViewById(R.id.bt_stop);bt_replay = (Button) findViewById(R.id.bt_replay);}/*** 播放* @param view*/public void play(View view) {String filepath = et_path.getText().toString().trim();File file = new File(filepath);if(file.exists()){try {mediaPlayer = new MediaPlayer();mediaPlayer.setDataSource(filepath);//设置播放的数据源。

android音乐播放器代码

android音乐播放器代码

81.});
82.
83.forwardBtn.setOnTouchListener(new OnTouchListener() { //点击“快进”按钮时回调
84. @Override
85. public boolean onTouch(View v, MotionEvent event) {
01./*变量声明*/
02.private ImageButton playBtn = null;//播放、暂停
03.private ImageButton latestBtn = null;//上一首
04.private ImageButton nextButton = null;//下一首
37.playBtn.setOnClickListener(new View.OnClickListener() { //点击“播放、暂停”按钮时回调
38. @Override
39. public void onClick(View v) {
testBtn = (ImageButton)findViewById(testBtn); //播放上一首按钮
31.nextButton = (ImageButton)findViewById(R.id.nextBtn); //播放下一首按钮
32.forwardBtn = (ImageButton)findViewById(R.id.forwardBtn); //快进按钮
64. play(); //开始播放
65. }
66.});
67.
68.nextButton.setOnClickListener(new View.OnClickListener(){//点击“播放下一首”按钮时回调

Android实现简单音乐播放器(MediaPlayer)

Android实现简单音乐播放器(MediaPlayer)

Android实现简单⾳乐播放器(MediaPlayer)Android实现简单⾳乐播放器(MediaPlayer),供⼤家参考,具体内容如下开发⼯具:Andorid Studio 1.3运⾏环境:Android 4.4 KitKat⼯程内容实现⼀个简单的⾳乐播放器,要求功能有:播放、暂停功能;进度条显⽰播放进度功能拖动进度条改变进度功能;后台播放功能;停⽌功能;退出功能;代码实现导⼊歌曲到⼿机SD卡的Music⽬录中,这⾥我导⼊了4⾸歌曲:仙剑六⾥⾯的《誓⾔成晖》、《剑客不能说》、《镜中⼈》和《浪花》,也推荐⼤家听喔(捂脸然后新建⼀个类MusicService继承Service,在类中定义⼀个MyBinder,有⼀个⽅法⽤于返回MusicService本⾝,在重载onBind()⽅法的时候返回public class MusicService extends Service {public final IBinder binder = new MyBinder();public class MyBinder extends Binder{MusicService getService() {return MusicService.this;}}@Overridepublic IBinder onBind(Intent intent) {return binder;}}在MusicService中,声明⼀个MediaPlayer变量,进⾏设置歌曲路径,这⾥我选择歌曲1作为初始化时候的歌曲private String[] musicDir = new String[]{Environment.getExternalStorageDirectory().getAbsolutePath() + "/Music/仙剑奇侠传六-主题曲-《誓⾔成晖》.mp3",Environment.getExternalStorageDirectory().getAbsolutePath() + "/Music/仙剑奇侠传六-主题曲-《剑客不能说》.mp3",Environment.getExternalStorageDirectory().getAbsolutePath() + "/Music/仙剑奇侠传六-主题曲-《镜中⼈》.mp3",Environment.getExternalStorageDirectory().getAbsolutePath() + "/Music/仙剑奇侠传六-主题曲-《浪花》.mp3"};private int musicIndex = 1;public static MediaPlayer mp = new MediaPlayer();public MusicService() {try {musicIndex = 1;mp.setDataSource(musicDir[musicIndex]);mp.prepare();} catch (Exception e) {Log.d("hint","can't get to the song");e.printStackTrace();}}设计⼀些歌曲播放、暂停、停⽌、退出相应的逻辑,此外我还设计了上⼀⾸和下⼀⾸的逻辑public void playOrPause() {if(mp.isPlaying()){mp.pause();} else {mp.start();}}public void stop() {if(mp != null) {mp.stop();try {mp.prepare();mp.seekTo(0);} catch (Exception e) {e.printStackTrace();}}}public void nextMusic() {if(mp != null && musicIndex < 3) {mp.stop();try {mp.reset();mp.setDataSource(musicDir[musicIndex+1]);musicIndex++;mp.prepare();mp.seekTo(0);mp.start();} catch (Exception e) {Log.d("hint", "can't jump next music");e.printStackTrace();}}}public void preMusic() {if(mp != null && musicIndex > 0) {mp.stop();try {mp.reset();mp.setDataSource(musicDir[musicIndex-1]);musicIndex--;mp.prepare();mp.seekTo(0);mp.start();} catch (Exception e) {Log.d("hint", "can't jump pre music");e.printStackTrace();}}}注册MusicService并赋予权限,允许读取外部存储空间<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/><service android:name="com.wsine.west.exp5_AfterClass.MusicService" android:exported="true"></service>在MainAcitvity中声明ServiceConnection,调⽤bindService保持与MusicService通信,通过intent的事件进⾏通信,在onCreate()函数中绑定Serviceprivate ServiceConnection sc = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName componentName, IBinder iBinder) {musicService = ((MusicService.MyBinder)iBinder).getService();}@Overridepublic void onServiceDisconnected(ComponentName componentName) {musicService = null;}};private void bindServiceConnection() {Intent intent = new Intent(MainActivity.this, MusicService.class);startService(intent);bindService(intent, sc, this.BIND_AUTO_CREATE);}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.activity_main);Log.d("hint", "ready to new MusicService");musicService = new MusicService();Log.d("hint", "finish to new MusicService");bindServiceConnection();seekBar = (SeekBar)this.findViewById(R.id.MusicSeekBar);seekBar.setProgress(musicService.mp.getCurrentPosition());seekBar.setMax(musicService.mp.getDuration());musicStatus = (TextView)this.findViewById(R.id.MusicStatus);musicTime = (TextView)this.findViewById(R.id.MusicTime);btnPlayOrPause = (Button)this.findViewById(R.id.BtnPlayorPause);Log.d("hint", Environment.getExternalStorageDirectory().getAbsolutePath()+"/You.mp3");}bindService函数回调onSerciceConnented函数,通过MusiceService函数下的onBind()⽅法获得binder对象并实现绑定通过Handle实时更新UI,这⾥主要使⽤了post⽅法并在Runnable中调⽤postDelay⽅法实现实时更新UI,Handle.post⽅法在onResume()中调⽤,使得程序刚开始时和重新进⼊应⽤时能够更新UI在Runnable中更新SeekBar的状态,并设置SeekBar滑动条的响应函数,使歌曲跳动到指定位置public android.os.Handler handler = new android.os.Handler();public Runnable runnable = new Runnable() {@Overridepublic void run() {if(musicService.mp.isPlaying()) {musicStatus.setText(getResources().getString(R.string.playing));btnPlayOrPause.setText(getResources().getString(R.string.pause).toUpperCase());} else {musicStatus.setText(getResources().getString(R.string.pause));btnPlayOrPause.setText(getResources().getString(R.string.play).toUpperCase());}musicTime.setText(time.format(musicService.mp.getCurrentPosition()) + "/"+ time.format(musicService.mp.getDuration()));seekBar.setProgress(musicService.mp.getCurrentPosition());seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {@Overridepublic void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {if (fromUser) {musicService.mp.seekTo(seekBar.getProgress());}}@Overridepublic void onStartTrackingTouch(SeekBar seekBar) {}@Overridepublic void onStopTrackingTouch(SeekBar seekBar) {}});handler.postDelayed(runnable, 100);}};@Overrideprotected void onResume() {if(musicService.mp.isPlaying()) {musicStatus.setText(getResources().getString(R.string.playing));} else {musicStatus.setText(getResources().getString(R.string.pause));}seekBar.setProgress(musicService.mp.getCurrentPosition());seekBar.setMax(musicService.mp.getDuration());handler.post(runnable);super.onResume();Log.d("hint", "handler post runnable");}给每个按钮设置响应函数,在onDestroy()中添加解除绑定,避免内存泄漏public void onClick(View view) {switch (view.getId()) {case R.id.BtnPlayorPause:musicService.playOrPause();break;case R.id.BtnStop:musicService.stop();seekBar.setProgress(0);break;case R.id.BtnQuit:handler.removeCallbacks(runnable);unbindService(sc);try {System.exit(0);} catch (Exception e) {e.printStackTrace();}break;case R.id.btnPre:musicService.preMusic();break;case R.id.btnNext:musicService.nextMusic();break;default:break;}}@Overridepublic void onDestroy() {unbindService(sc);super.onDestroy();}在Button中赋予onClick属性指向接⼝函数<Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/BtnPlayorPause"android:text="@string/btnPlayorPause"android:onClick="onClick"/>效果图打开界⾯->播放⼀会⼉进度条实时变化->拖动进度条->点击暂停->点击Stop->点击下⼀⾸(歌曲时间变化)->点击上⼀⾸->点击退出⼀些总结读取SD卡内存的时候,应该使⽤android.os.Environment库中的getExternalStorageDirectory()⽅法,然⽽并不能⽣效。

音乐播放器程序源代码及注释

音乐播放器程序源代码及注释

音乐播放器程序源代码及注释:#include <reg52.h>#define uchar unsigned char#define uint unsigned intsbit duan=P2^6;sbit key1=P3^2;//按key1可切换花样sbit key2=P3^3;//按key2可切换歌曲sbit fm=P2^4;//蜂鸣器连续的IO口sbit P30=P3^0;//矩阵键盘的一列uchar code huayang1[]={0x7f,0xbf,0xdf,0xef,0xf7,0xfb,0xfd,0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf};//花样1uchar code huayang2[]={0x7f,0xfe,0xbf,0xfd,0xdf,0xfb,0xef,0xf7,0xef,0xfb,0xdf,0xfd,0xbf,0xfe};//花样2uchar code huayang3[]={0x7f,0x3f,0x1f,0x0f,0x07,0x03,0x01,0x0,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff}; char codehuayang4[]={ 0x55,0xaa,0xcc,0x33,0x99,0x66,0x0f,0xf0}; uchar count1;//花样标志uchar count2;//歌曲标志uchar timeh,timel,i;//编程规则:字节高位是简谱,低位是持续时间,//代表多少个十六分音符//1-7代表中央C调,8-E代表高八度,0代表停顿//最后的0是结束标志uchar code qnzl[]={ //千年之恋0x12,0x22,0x34,0x84,0x74,0x54,0x38,0x42,0x32,0x22,0x42,0x34,0x84,0 x72,0x82,0x94,0xA8,0x08,//前奏0x32,0x31,0x21,0x32,0x52,0x32,0x31,0x21,0x32,0x62,//竹林的灯火到过的沙漠0x32,0x31,0x21,0x32,0x82,0x71,0x81,0x71,0x51,0x32,0x22,//七色的国度不断飘逸风中0x32,0x31,0x21,0x32,0x52,0x32,0x31,0x21,0x32,0x62,//有一种神秘灰色的旋涡0x32,0x31,0x21,0x32,0x83,0x82,0x71,0x72,0x02,//将我卷入了迷雾中0x63,0xA1,0xA2,0x62,0x92,0x82,0x52,//看不清的双手0x31,0x51,0x63,0x51,0x63,0x51,0x63,0x51,0x62,0x82,0x7C,0x02, //一朵花传来谁经过的温柔0x61,0x71,0x82,0x71,0x62,0xA2,0x71,0x76,//穿越千年的伤痛0x61,0x71,0x82,0x71,0x62,0x52,0x31,0x36,//只为求一个结果0x61,0x71,0x82,0x71,0x62,0xA3,0x73,0x62,0x53,//你留下的轮廓指引我0x42,0x63,0x83,0x83,0x91,0x91,//黑夜中不寂寞0x61,0x71,0x82,0x71,0x62,0x0A2,0x71,0x76,//穿越千年的哀愁0x61,0x71,0x82,0x71,0x62,0x52,0x31,0x36,//是你在尽头等我0x61,0x71,0x82,0x71,0x62,0xA3,0x73,0x62,0x53,//最美丽的感动会值得0x42,0x82,0x88,0x02,0x74,0x93,0x89,0xff//结束标志//用一生守候};uchar code jmszl[]={ //寂寞沙洲冷0x12,0x12,0x22,0x32,0x31,0x22,0x21,0x22,//自你走后心憔悴0x21,0x31,0x51,0x52,0x31,0x52,0x61,0x15,0x14,//白色油桐风中纷飞0x51,0x52,0x31,0x52,0x62,0x13,0x11,0x13,0x32,0x28,0x08,0x28, //落花似人有情这个季节0x31,0x32,0x31,0x32,0x11,0x21,0x51,0x52,0x51,0x52,//河畔的风放肆拼命地吹0x51,0x51,0x31,0x32,0x31,0x32,0x81,0x72,0x63,//不断拨弄离人的眼泪0x62,0x71,0x81,0x72,0x61,0x61,0x52,0x31,0x21,0x32,0x51,0x54, //那样浓烈的爱再也无法给0x22,0x12,0x11,0x12,0x11,0x12,0x12,0x14,0x26,0x32,0x26,//伤感一夜一夜0x32,0x61,0x51,0x51,0x31,0x31,0x21,0x31,0x51,0x61,0x51,0x31,0x51, //当记忆的线缠绕过往支离破碎0x02,0x32,0x81,0x81,0x81,0x81,0x62,0x52,0x34,//是慌乱占据了心扉0x31,0x81,0x81,0x81,0x61,0x91,0x82,//有花儿伴着蝴蝶0x51,0x51,0x51,0x51,0x31,0x61,0x53,//孤雁可以双飞0x21,0x11,0x21,0x11,0x22,0x11,0x21,0x26,//夜深人静独徘徊0x32,0x61,0x51,0x51,0x31,0x31,0x21,0x31,0x51,0x61,0x51,0x31,0x51,0 x52,//当幸福恋人寄来红色分享喜悦0x31,0x31,0x81,0x81,0x81,0x61,0x91,0x81,0x61,0x31,0x56,//闭上双眼难过头也不敢回0x32,0x32,0x81,0x81,0x81,0x81,0x91,0x81,0x61,0x81,0x61,0x51,0x31,0 x51,0x34,//仍然捡尽寒枝不肯安歇微带着后悔0x21,0x31,0x51,0x31,0x21,0x11,0x61,0x21,0x16,//寂寞沙洲我该思念谁0xff};uchar code cuzhi[]={0xff,0xff,//占位0xFC,0x8E,//中央C调1-70xFC,0xED,0xFD,0x43,0xFD,0x6A,0xFD,0xB3,0xFD,0xF3,0xFE,0x2D,0xFE,0x47, //高八度1-70xFE,0x76,0xFE,0xA1,0xFE,0xC7,0xFE,0xD9,0xFE,0xF9,0xFF,0x16};ucharyinyue[]={0xff,0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f,0x0,0x0}; //将音调转化为对应的LED样式void delay1(uint z); //延时1MSvoid delay(uint z); //延时165MS,即十六分音符void song();void beep();//蜂鸣器叫一声main(){ uchar x;count1=0;//流水灯无花样count2=1;//唱第一首歌P30=0;//选取矩阵键盘的一列EA=1;//开总中断EX0=1;//开外部中断0IT0=1;//外部中断0下降沿触发方式EX1=1;//开外部中断1IT1=1;//外部中断1下降沿触发方式TMOD=0x01;//定时器0工作在方式1 TH0=0;TL0=0;ET0=1;while(1){if(count1!=0){switch(count1){case 1:for(x=0;x<14;x++) {duan=1;P1=huayang1[x]; beep();delay1(300); duan=0;if(count1!=1) break;}break;case 2:for(x=0;x<14;x++) {duan=1;P1=huayang2[x]; beep();delay1(300); duan=0;if(count1!=2) break;}break;case 3:for(x=0;x<16;x++) {duan=1;P1=huayang3[x]; beep();delay1(300); duan=0;if(count1!=3) break;}break;case 4:for(x=0;x<8;x++) {duan=1;P1=huayang4[x]; beep();delay1(300); duan=0;if(count1!=4) break;}break;}}else{song();delay1(1000);}}}void int0() interrupt 0 {EA=0;//关总中断delay1(1);//去抖if(key1==0){count2=0;//不让蜂鸣器唱歌TR0=0;count1++;if(count1==5)count1=1;}EA=1;//开总中断}void int1() interrupt 2 {EA=0;//关总中断delay1(1);//去抖if(key2==0){count1=0;//流水灯无花样TR0=1;i=0;//从头开始唱count2++;if(count2==3)count2=1;}EA=1;//开总中断}void timer0() interrupt 1 //用于产生各种音调{ TH0=timeh;TL0=timel;fm=~fm;}void song(){uint temp;uchar jp;//jp是简谱i=0;while(1){ if(count2==0){break;}if(count2==1) //选曲temp=qnzl[i];if(count2==2)temp=jmszl[i];if(temp==0xff)break;jp=temp/16; //取数的高4位duan=1;P1=yinyue[jp];duan=0;if(jp!=0){timeh=cuzhi[jp*2];timel=cuzhi[jp*2+1];}else{TR0=0;fm=1;//关蜂鸣器}delay(temp%16); //取数的低4位TR0=0; //唱完一个音停10MSfm=1;delay1(10);TR0=1;i++;}TR0=0;fm=1;}void delay(uint z) //延时165MS,即十六分音符{ uint x,y; for(x=z;x>0;x--)for(y=19000;y>0;y--);}void delay1(uint z) //延时1MS{ uint x,y;for(x=z;x>0;x--)for(y=112;y>0;y--);}void beep() //蜂鸣器叫一声{ uchar i;for(i=0;i<50;i++){ fm=~fm;delay1(1);}fm=1;}。

android开发一个简单的Android音乐播放器

android开发一个简单的Android音乐播放器
创建一个MusicServiceActivity类启动service类:
package com.basi;
import android.app.Activity; import android.content.Intent;
import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast;
public class MusicServiceActivity extends Activity {
private static String TAG = "MusicService";
@Override public void onCreate(Bundle savedInstanceState) {
mPlayer.start(); super.onStart(intent, startId);
}
@Override public void onDestroy() { Toast.makeText(this, "MusicSevice onDestroy()", Toast.LENGTH_SHORT)
super.onCreate(savedInstanceState); setContentView(yout.main);
Toast.makeText(this, "MusicServiceActivity", Toast.LENGTH_SHORT).show(); Log.e(TAG, "MusicServiceActivity"); initlizeViews(); }
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
图播放器基本用例图
用例分析
用例名称:启动软件
参与者:用户
目标:使得用户启动软件并加载手机和sd卡上的音频文件到播放列表
前置条件:无
基本事件流:1.用户启动软件
2.播放器将播放列表中的当前的歌曲
用例名称:播放
参与者:用户
目标:使得用户可以播放在播放列表中选中的歌曲
前置条件:播放器正在运行
基本事件流:1.用户单击“播放”按钮
根据项目的目标,我们可获得项目系统的基本需求,以下从不同角度来描述系统的需求,并且使用用例图来描述,系统的功能需求,我们分成四部分来概括,即播放器的基本控制需要,播放列表管理需求,播放器友好性需求和播放器扩展卡需求。以下分别描述:
假设安装了音乐播放器的用户是系统的主要设计对象,其拥有以下操作,启动软件、播放音乐、暂停播放、停止播放、退出软件,其用例图如下
(1)通过本次开发解决了诸如SD卡音乐文件搜索并显示、联网搜索歌曲等难题,对安卓的开发有了更深入的认识。
(2)通过对Android手机平台的音乐播放器软件的开发,使我对Android音乐播放器系统的整体设计有一个深入的了解,对整个流程也会有一个清晰的认识。开发Android音乐播放器,要抓住开发的核心部分,音乐播放器大体由播放主界面、播放列表、菜单、播放设置、文件浏览、歌曲搜索六大核心组成。
Android:是谷歌于2007年公布的开放式源代码手机系统,它的开放性就优于其它封闭式的手机系统,因此,任何人都可能根据自己的喜好将手机系统中的所有功能重新编写。这使得越来越多的人关注这个操作系统。本次作品音乐播放器就是基于Android平台的。
现今社会生活紧张,而欣赏音乐是其中最好的舒缓压力的方式之一,本项目的目的是开发一个可以播放主流音乐文件格式的播放器,本设计实现的主要功能是播放Mp3,Wav多种格式的音乐文件,并且能够控制播放,暂停,停止,播放列等基本播放控制功能,界面简明,操作简单。
基于android平台的音乐播放器开发
实验报告
学生姓名:温从林
学号:0215
班级:计自1201
第一章
Байду номын сангаас
当今社会的生活节奏越来越快,人们对手机的要求也越来越高,由于手机市场发展迅速,使得手机操作系统也出现了不同各类,现在的市场上主要有三个手机操作系统,Windows mobile,symbian,以及谷歌的Android操作系统,其中占有开放源代码优势的Android系统有最大的发展前景。那么能否在手机上拥有自己编写的个性音乐播放器呢?能的,谷歌Android系统就能做到。本文的音乐播放器就是基于谷歌Android手机平台的播放器。
getMenuInflater().inflate menu);
returntrue;
}
@Override
publicbooleanonOptionsItemSelected(MenuItem item) {
The action bar will
intid = ();
if(id == {
returntrue;
Step4.点击暂停,音乐暂停
Step5.点击播放转到step3
Step6.点击停止停止播放音乐
Step7.点击退出。
图音乐播放器流程图
第四章
软件部署
系统编译生成apk文件,将apk文件拷到手机或者sd卡中,直接打开即可安装。
启动软件
打开软件后的界面
歌曲列表界面
播放界面
收藏界面
在线搜索音乐界面
第5章
(3)本次程序设计,对播放器的系统结构框架做了精心的构思与设计,采用主要开发工具是+Java语言的支持,Android Development Tool的插件,和Android版本的全面结合,才使整个音乐播放器系统得以实现。
以下给出功能实现代码,布局,风格等代码量过大,放在压缩文件中
:
packageclassMainActivityextendsActionBarActivity {
2.播放器将播放列表中的当前的歌曲
用例名称:暂停
参与者:用户
目标:使得用户可以暂停正在播放的歌曲
前置条件:歌曲正在播放且未停止和暂停
基本事件流:1.用户单击“暂停”按钮
2.播放器将暂停当前的歌曲
用例名称:停止
参与者:用户
目标:使得用户可以停止正在播放的歌曲
前置条件:歌曲正在播放或暂停
基本事件流:1.用户单击“停止”按钮
2.播放器将停止当前播放的歌曲
用例名称:退出
参与者:用户
目标:使得用户退出或者后台播放音乐
前置条件:程序在运行
基本事件流:1.用户按返回键
2.播放器退出或者进入后台播放
第三章
软件播放流程图
Step1.启动软件后,软件自动检索手机和sd卡的音频文件,并组织显示成列表.
Step2.点击列表的歌曲名字。
Step3.播放音乐。
try{
sleep(2500);
}catch(InterruptedException e) {
();
}
finish();
Intent intent =newIntent, ;
startActivity(intent);
}
};
();
}
@Override
publicbooleanonCreateOptionsMenu(Menu menu) {
本项目是一款基于Android手机平台的音乐播放器,使Android手机拥有个性的多媒体播放器,使手机显得更生动灵活化,与人们更为接近,让手机主人随时随地处于音乐视频的旋律之中。使人们的生活更加多样化。也使设计者更加熟练Android的技术和其它在市场上的特点。
开发环境
Eclipse、Android SDK
}
return(item);
}
/**
* A placeholder fragment containing a simple view.
*/
publicstaticclassPlaceholderFragmentextendsFragment {
publicPlaceholderFragment() {
@Override
protectedvoidonCreate(Bundle savedInstanceState) {
(savedInstanceState);
requestWindowFeature;
setContentViewThread thread =newThread() {
publicvoidrun() {
相关文档
最新文档