音樂播放上一首暫停下一首進度條
佈局檔案:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="net.bwie.mediaplayer.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/current_time_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="當前時間"/>
<TextView
android:id="@+id/total_time_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="全部時間"/>
<SeekBar
android:id="@+id/seek_bar"
style="?android:progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_toLeftOf="@id/total_time_tv"
android:layout_toRightOf="@id/current_time_tv"/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/previous_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="上一曲"/>
<Button
android:id="@+id/play_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="播放/暫停"/>
<Button
android:id="@+id/next_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="下一曲"/>
</LinearLayout>
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#f00"
android:dividerHeight="2dp"/>
</LinearLayout>
許可權:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
package net.bwie.mediaplayer;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import net.bwie.mediaplayer.bean.MediaInfo;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* 1、查詢全部歌曲資訊並展示(ContentProvider資料庫)
* 2、點選對應歌曲播放/暫停
* 3、播放/暫停按鈕。上一首/下一首
* 注意:設定外部儲存許可權
* build.gradle中targetSdkVersion 22
* <p>
* 進度條部分
* 1、進度條跟隨歌曲進度而變化
* 實現週期性改變進度條位置:1、Handler,2、TimerTask定時器
* 2、拖動進度條讓MediaPlayer播放對應位置的聲音
* SeekBar繫結監聽器
* MediaPlayer繫結播放完畢監聽器,實現自動播放下一曲
*/
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, View.OnClickListener, SeekBar.OnSeekBarChangeListener, MediaPlayer.OnCompletionListener {
protected ListView mListView;
protected Button mPreviousBtn;
protected Button mPlayBtn;
protected Button mNextBtn;
protected TextView mCurrentTimeTv;
protected TextView mTotalTimeTv;
protected SeekBar mSeekBar;
private List<MediaInfo> mMediaInfoList;
private MediaPlayer mMediaPlayer;
// 記錄當前播放歌曲的位置
private int mCurrentPosition;
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
// 展示給進度條和當前時間
int progress = mMediaPlayer.getCurrentPosition();
mSeekBar.setProgress(progress);
mCurrentTimeTv.setText(parseTime(progress));
// 繼續定時傳送資料
updateProgress();
return true;
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_main);
initView();
mMediaInfoList = getDatas();
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1,
mMediaInfoList);
mListView.setAdapter(adapter);
mListView.setOnItemClickListener(this);
}
private void initView() {
mListView = (ListView) findViewById(R.id.list_view);
mPreviousBtn = (Button) findViewById(R.id.previous_btn);
mPreviousBtn.setOnClickListener(MainActivity.this);
mPlayBtn = (Button) findViewById(R.id.play_btn);
mPlayBtn.setOnClickListener(MainActivity.this);
mNextBtn = (Button) findViewById(R.id.next_btn);
mNextBtn.setOnClickListener(MainActivity.this);
mCurrentTimeTv = (TextView) findViewById(R.id.current_time_tv);
mTotalTimeTv = (TextView) findViewById(R.id.total_time_tv);
mSeekBar = (SeekBar) findViewById(R.id.seek_bar);
// SeekBar繫結監聽器,監聽拖動到指定位置
mSeekBar.setOnSeekBarChangeListener(this);
}
// 獲取系統媒體資料庫中的音訊多媒體資訊
private List<MediaInfo> getDatas() {
List<MediaInfo> list = new ArrayList<>();
// 使用內容解析者訪問系統提供的資料庫
Cursor cursor = getContentResolver()
.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
null,
null,
null,
MediaStore.Audio.Media.DEFAULT_SORT_ORDER);// 預設排序順序
// 如果遊標讀取時還有下一個資料,讀取
int idIndex = cursor.getColumnIndex(MediaStore.Audio.Media._ID);//獲取列名對應的索引
int titleIndex = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);// 標題
int artistIndex = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);// 藝術家
int uriIndex = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);// 檔案路徑
while (cursor.moveToNext()) {
// 根據索引值獲取對應列名中的數值
long _id = cursor.getLong(idIndex);
String title = cursor.getString(titleIndex);
String artist = cursor.getString(artistIndex);
String uri = cursor.getString(uriIndex);
MediaInfo mediaInfo = new MediaInfo(_id, uri, title, artist);
list.add(mediaInfo);
}
for (MediaInfo mediaInfo : list) {
Log.d("1507", "" + mediaInfo.toString());
}
return list;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mCurrentPosition = position;
changeMusic(mCurrentPosition);
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.previous_btn) {// 上一首
changeMusic(--mCurrentPosition);
} else if (view.getId() == R.id.play_btn) {// 播放/暫停
// 首次點選播放按鈕,預設播放第0首
if (mMediaPlayer == null) {
changeMusic(0);
} else {
playOrPause();
}
} else if (view.getId() == R.id.next_btn) {// 下一首
changeMusic(++mCurrentPosition);
}
}
// 播放或暫停
private void playOrPause() {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
} else {
mMediaPlayer.start();
}
}
// 基本資料型別和String在方法呼叫中傳遞的是值
// 其他資料型別在方法呼叫中傳遞的是引用
// 切歌
private void changeMusic(int position) {
if (position < 0) {
mCurrentPosition = position = mMediaInfoList.size() - 1;
} else if (position > mMediaInfoList.size() - 1) {
mCurrentPosition = position = 0;
}
if (mMediaPlayer == null) {
mMediaPlayer = new MediaPlayer();
// 繫結播放完畢監聽器
mMediaPlayer.setOnCompletionListener(this);
}
try {
// 切歌之前先重置,釋放掉之前的資源
mMediaPlayer.reset();
// 設定播放源
mMediaPlayer.setDataSource(mMediaInfoList.get(position).getUri());
// 開始播放前的準備工作,載入多媒體資源,獲取相關資訊
mMediaPlayer.prepare();
// 開始播放
mMediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "播放錯誤", Toast.LENGTH_SHORT).show();
}
// 切歌時重置進度條並展示歌曲時長
mSeekBar.setProgress(0);
mSeekBar.setMax(mMediaPlayer.getDuration());
mTotalTimeTv.setText(parseTime(mMediaPlayer.getDuration()));
updateProgress();
}
// 每間隔1s通知更新進度
private void updateProgress() {
// 使用Handler每間隔1s傳送一次空訊息,通知進度條更新
Message msg = Message.obtain();// 獲取一個現成的訊息
mHandler.sendMessageDelayed(msg, INTERNAL_TIME);
}
// 解析時間
private String parseTime(int oldTime) {
SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");// 時間格式
String newTime = sdf.format(new Date(oldTime));
return newTime;
}
private static final int INTERNAL_TIME = 1000;// 音樂進度間隔時間
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
// 當手停止拖拽進度條時執行該方法
// 獲取拖拽進度
// 將進度對應設定給MediaPlayer
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
int progress = seekBar.getProgress();
mMediaPlayer.seekTo(progress);
}
@Override
public void onCompletion(MediaPlayer mp) {
// 當歌曲播放完畢,切歌到下一首
changeMusic(++mCurrentPosition);
}
}
//Bean類
package net.bwie.mediaplayer.bean;
public class MediaInfo {
private long _id;
private String uri;// 路徑
private String title;
private String artist;// 藝術家
public MediaInfo(long _id, String uri, String title, String artist) {
this._id = _id;
this.uri = uri;
this.title = title;
this.artist = artist;
}
public long get_id() {
return _id;
}
public void set_id(long _id) {
this._id = _id;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
@Override
public String toString() {
return "MediaInfo{" +
"_id=" + _id +
", uri='" + uri + '\'' +
", title='" + title + '\'' +
", artist='" + artist + '\'' +
'}';
}
}