android 简单的音乐播放器实现播放模式的切换
生活随笔
收集整理的這篇文章主要介紹了
android 简单的音乐播放器实现播放模式的切换
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
以前寫(xiě)過(guò)一篇簡(jiǎn)單的音樂(lè)播放器,但是這個(gè)播放器沒(méi)有實(shí)現(xiàn)播放模式的切換,在項(xiàng)目中要實(shí)現(xiàn)兩個(gè)播放模式,循環(huán)播放和隨機(jī)播放,經(jīng)過(guò)這兩天的努力搞定了,界面比較粗糙。可以先看一下前面的簡(jiǎn)單音樂(lè)播放器,詳細(xì)的就不說(shuō)了,直接把代碼放上去,詳細(xì)的看前面的博文。
布局文件
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@drawable/background"android:orientation="vertical" ><LinearLayout android:id="@+id/linearlayout"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_alignParentTop="true"><Button android:id="@+id/list1"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="放松音樂(lè)"android:textColor="#ffffff"android:textSize="30sp"/><Button android:id="@+id/list2"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="冥想"android:textColor="#ffffff"android:textSize="30sp"/></LinearLayout><TextViewandroid:id="@+id/updatevedio"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@id/linearlayout"android:textSize="30sp"android:textColor="#ffffff"android:text="音樂(lè)列表"/> <ListViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_below="@id/updatevedio"android:id="@+id/lv"></ListView> <TextView android:id="@+id/name"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentBottom="true"android:layout_alignParentLeft="true"android:maxEms="8" android:singleLine="true"android:ellipsize="marquee"android:paddingBottom="20dp"android:textSize="20sp"android:textColor="#ffffff"/> <LinearLayout android:id="@+id/linearLayout"android:layout_alignParentBottom="true"android:layout_centerInParent="true"android:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="horizontal"><Button android:id="@+id/model"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="@drawable/xunhuan"/><Button android:id="@+id/back"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="@drawable/shangyishou"/><Button android:id="@+id/pause"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="@drawable/zanting"/><Button android:id="@+id/next"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="@drawable/xiayishou"/></LinearLayout><SeekBar android:id="@+id/seekBar"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_above="@id/linearLayout"/></RelativeLayout>添加了兩個(gè)按鈕,分別為兩個(gè)播放列表。
實(shí)現(xiàn)的activity
package cn.edu.cqu.project_test_activity; import java.io.File; import java.util.ArrayList; import java.util.HashMap;import com.zghaikun.sleep_client.R;import android.app.Activity; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast;public class MP3ListActivity extends Activity implements OnClickListener{private static final String LOG = "MP3ListActivity";private ListView lv; private SeekBar seekBar;private Button modelButton;private Button backButton;private Button pauseButton;private Button nextButton;private TextView nameText;private ArrayList<HashMap<String, String>> musicList;private ArrayList<String> musicpathlist;private String path = Environment.getExternalStorageDirectory().getPath();private String musicpath;private String musicname;private MediaPlayer mediaPlayer;public int songNum; // 當(dāng)前播放的歌曲在List中的下標(biāo) private boolean isStartTrackingTouch; private Handler handler = new Handler(); private int Sequence = 1;//順序播放private int Shuffle = 2;//隨機(jī)播放private Button fristButton;private Button secondButton;String music = "/Music";String mp3 = "/mp3";int i = 0;int flag = 0;@Overrideprotected void onCreate(Bundle savedInstanceState) {this.requestWindowFeature(Window.FEATURE_NO_TITLE);super.onCreate(savedInstanceState);setContentView(R.layout.mp3_list); lv = (ListView) findViewById(R.id.lv); seekBar = (SeekBar) findViewById(R.id.seekBar);modelButton = (Button) findViewById(R.id.model);backButton = (Button) findViewById(R.id.back);pauseButton = (Button) findViewById(R.id.pause);nextButton = (Button) findViewById(R.id.next);nameText = (TextView) findViewById(R.id.name);fristButton = (Button) findViewById(R.id.list1);secondButton = (Button) findViewById(R.id.list2);musicList = new ArrayList<HashMap<String, String>>(); musicpathlist=new ArrayList<String>();mediaPlayer = new MediaPlayer();//獲得視頻列表,默認(rèn)顯示放松音樂(lè)mp3List(music);fristButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {//清空列表和保存的地址信息musicpathlist.clear();musicList.clear();//獲得視頻列表mp3List(music);}});secondButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {//清空列表和保存的地址信息musicpathlist.clear();musicList.clear();//冥想列表mp3List(mp3);}});pauseButton.setOnClickListener(this);backButton.setOnClickListener(this);modelButton.setOnClickListener(this);nextButton.setOnClickListener(this);//進(jìn)度條監(jiān)聽(tīng)器 seekBar.setOnSeekBarChangeListener(new MySeekBarListener()); nextButton.setOnTouchListener(new OnTouchListener() {@Overridepublic boolean onTouch(View arg0, MotionEvent arg1) {// TODO Auto-generated method stubif(arg1.getAction() == MotionEvent.ACTION_DOWN){ arg0.setBackgroundResource(R.drawable.xiayishou_anxia); } else if(arg1.getAction() == MotionEvent.ACTION_UP){ arg0.setBackgroundResource(R.drawable.xiayishou); } return false;}});backButton.setOnTouchListener(new OnTouchListener() {@Overridepublic boolean onTouch(View view, MotionEvent event) {// TODO Auto-generated method stubif(event.getAction() == MotionEvent.ACTION_DOWN){ view.setBackgroundResource(R.drawable.shangyishou_anxia); } else if(event.getAction() == MotionEvent.ACTION_UP){ view.setBackgroundResource(R.drawable.shangyishou); } return false;}}); // pauseButton.setOnTouchListener(new OnTouchListener() { // // @Override // public boolean onTouch(View arg0, MotionEvent arg1) { // // TODO Auto-generated method stub // int i = 0; // i++; // if(i % 2 == 0){ // // } // return false; // } // });} //獲得視頻列表private void mp3List(String music){ if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // File path = Environment.getExternalStorageDirectory();// 獲得SD卡路徑 System.out.println("path-------》" + path);//File[] files = path.listFiles();// 讀取 String musicPath = path + music; getFileName(musicPath); //視頻列表Log.i(LOG, musicPath);} SimpleAdapter adapter = new SimpleAdapter(this, musicList, R.layout.sd_list, new String[] { "name" }, new int[] { R.id.mp4 }); lv.setAdapter(adapter);for (int i = 0; i < musicList.size(); i++) { Log.i(LOG, "list. name: " + musicList.get(i)); }lv.setOnItemClickListener(new ListView.OnItemClickListener(){@Overridepublic void onItemClick(AdapterView<?> arg0, View view, int position,long id) { // //順序播放 // if(flag == 0){ // songNum = position; // } // //隨機(jī)播放 // else if(flag == 1){ // songNum = (int)(Math.random()*musicList.size());; // }songNum = position;initMediaPlayer(songNum);} }); }//僅搜索當(dāng)前目錄下的文件 private void getFileName(String url) { File files = new File(url);File[] file = files.listFiles();//先判斷目錄是否為空,否則會(huì)報(bào)空指針if (files != null) { for (File f : file) { String fileName = f.getName(); if (fileName.endsWith(".mp3")||fileName.endsWith(".wav")) { HashMap<String, String> map = new HashMap<String, String>(); String s = fileName.substring(0,fileName.lastIndexOf(".")).toString(); //獲取文件的地址musicpath = f.getPath();Log.i(LOG, "文件名mp3或wav:: " + s); map.put("name", fileName);// map.put("mp3", f.getName()); musicpathlist.add(musicpath);musicList.add(map); } } } }//進(jìn)度條監(jiān)控private final class MySeekBarListener implements OnSeekBarChangeListener { //移動(dòng)觸發(fā) public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { } //起始觸發(fā) public void onStartTrackingTouch(SeekBar seekBar) { isStartTrackingTouch = true; } //結(jié)束觸發(fā) public void onStopTrackingTouch(SeekBar seekBar) { mediaPlayer.seekTo(seekBar.getProgress()); isStartTrackingTouch = false; } } //如果是順序播放private void initMediaPlayer(int songNum){musicname = musicpathlist.get(songNum); Log.i(LOG, musicname);if (musicname != null) {try {mediaPlayer.reset(); //重置多媒體 //指定音頻文件地址mediaPlayer.setDataSource(musicname);//這是一個(gè)地址String path = musicpathlist.get(songNum);String Text[] = path.split("/");Log.i(LOG, Text[5]);//設(shè)置當(dāng)前播放文件nameText.setText(Text[Text.length - 1]);Log.i(LOG, "播放");//準(zhǔn)備播放mediaPlayer.prepare();start(); // if (!mediaPlayer.isPlaying()) { // mediaPlayer.start(); // System.out.println("開(kāi)始播放"); // }} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}@Overridepublic void onClick(View v) {// TODO Auto-generated method stubswitch (v.getId()) {case R.id.pause:pauseButton.setBackgroundResource(R.drawable.jixu);Toast.makeText(getApplicationContext(), "暫停", Toast.LENGTH_SHORT).show();pause();break;case R.id.next:next();break;case R.id.back:back();break;case R.id.model:i++;if(i % 2 == 1){Toast.makeText(getApplicationContext(), "隨機(jī)播放", Toast.LENGTH_SHORT).show();//產(chǎn)生一個(gè)隨機(jī)數(shù) // songNum = (int)(Math.random()*musicList.size()); // System.out.println("song---" + songNum); // initMediaPlayer(songNum); //隨機(jī)播放falgflag = 1;modelButton.setBackgroundResource(R.drawable.suiji);}else{Toast.makeText(getApplicationContext(), "循環(huán)播放", Toast.LENGTH_SHORT).show();//循環(huán)播放flag = 0;modelButton.setBackgroundResource(R.drawable.xunhuan);}break;default:break;}}public void start() { try { mediaPlayer.start();//開(kāi)始播放 //設(shè)置進(jìn)度條長(zhǎng)度 seekBar.setMax(mediaPlayer.getDuration()); //發(fā)送一個(gè)Runnable, handler收到之后就會(huì)執(zhí)行run()方法 handler.post(new Runnable() { public void run() { // 更新進(jìn)度條狀態(tài) if (!isStartTrackingTouch) //獲取當(dāng)前播放音樂(lè)的位置seekBar.setProgress(mediaPlayer.getCurrentPosition()); // 1秒之后再次發(fā)送 handler.postDelayed(this, 1000); } });//setOnCompletionListener 當(dāng)當(dāng)前多媒體對(duì)象播放完成時(shí)發(fā)生的事件 mediaPlayer.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer arg0) { next();//如果當(dāng)前歌曲播放完畢,自動(dòng)播放下一首. } }); } catch (Exception e) { Log.v("MusicService", e.getMessage()); } } public void next() { Toast.makeText(getApplicationContext(), "下一首", Toast.LENGTH_SHORT).show();if(flag == 0){songNum = songNum == musicList.size() - 1 ? 0 : songNum + 1; }else if(flag == 1){songNum = (int)(Math.random()*musicList.size());}initMediaPlayer(songNum); } public void back() { Toast.makeText(getApplicationContext(), "上一首", Toast.LENGTH_SHORT).show();if(flag == 0){//songNum = songNum == 0 ? musicList.size() - 1 : songNum - 1; songNum = songNum - 1 < 0 ? musicList.size() - 1 : songNum - 1; }else if(flag == 1){songNum = (int)(Math.random()*musicList.size());}initMediaPlayer(songNum); } public void pause() { if (mediaPlayer.isPlaying()) {Toast.makeText(getApplicationContext(), "繼續(xù)", Toast.LENGTH_SHORT).show();pauseButton.setBackgroundResource(R.drawable.zanting);mediaPlayer.pause(); }else mediaPlayer.start(); } public void stop() { if (mediaPlayer.isPlaying()) { mediaPlayer.stop(); } } @Overrideprotected void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();if (mediaPlayer != null) {mediaPlayer.stop();//mediaPlayer.release();}} }
定義了一個(gè)flag,切換model按鈕設(shè)置flag的值, 當(dāng)flag的值為0時(shí)為循環(huán)播放,flag的值為1時(shí)為隨機(jī)播放,并使用songNum = (int)(Math.random()*musicList.size());產(chǎn)生隨機(jī)數(shù)進(jìn)行隨機(jī)播放。
與50位技術(shù)專家面對(duì)面20年技術(shù)見(jiàn)證,附贈(zèng)技術(shù)全景圖
總結(jié)
以上是生活随笔為你收集整理的android 简单的音乐播放器实现播放模式的切换的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 一汽解放j6l500马力有液力缓速器吗?
- 下一篇: 嘉陵200用啥机油?