环境:Api26,gradle 4.4
主要功能:
1.读取本地音乐文件
2.选取音乐播放
3.随机播放
注:仅仅分析关键业务的代码,完整的项目见github
1.读取本地音乐文件并在列表中显示
直接上代码:
void getAllMusic(){
Cursor cursor = this.getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
null,
null,
null,
MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
list_music_pojo = new ArrayList<MusicPOJO>();
if(cursor.moveToFirst()){
do{
MusicPOJO pojo = new MusicPOJO();
pojo.setName(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)));
pojo.setPath(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)));
list_name.add(pojo.getName());
list_music_pojo.add(pojo);
}while (cursor.moveToNext());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list_name);
list_view_music.setAdapter(adapter);
}
android系统会在sqlite表中存储音乐文件的相关数据,包括音乐名称,音乐路径,音乐的歌手,专辑等等
我这里使用Cursor从sqlite中读取音乐文件的信息,主要是名称和物理路径,分别用以列表显示和播放路径设置
list_view_music.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
path = getPathByName(list_name.get(i));
binder.setData(path);
binder.setAllMusic(list_music_pojo);
startService(intent_service);
Intent intent = new Intent(MainActivity.this,MusicPlay.class);
startActivity(intent);
}
});
设置ListView的监听事件,点击任意一首音乐则会通过定义在Service类中的binder传递至service实体,service调用
public int onStartCommand(Intent intent, int flags, int startId) {}方法开始运行音乐播放的流程
public int onStartCommand(Intent intent, int flags, int startId) {
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer arg0) {
mediaPlayer.reset();
try {
mediaPlayer.setDataSource(randomPlay());
mediaPlayer.prepare();
mediaPlayer.start();
}catch (Exception e){
e.printStackTrace();
}
}
});
}catch (Exception e){
}
return super.onStartCommand(intent, flags, startId);
}
这里使用了android原生的MediaPlayer来播放音乐文件,其中setOnCompletionListener方法主要考虑到延续播放的功能,设置音乐结束监听,然后从音乐列表中随机获取音乐继续播放,逻辑还是相当清楚的
最后贴上完整的文件代码吧,
MainActivity.java
package com.example.administrator.mmusic;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.os.IBinder;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import static java.security.AccessController.getContext;
public class MainActivity extends AppCompatActivity implements ServiceConnection {
private ListView list_view_music;
private List<MusicPOJO> list_music_pojo;
private List<String> list_name = new ArrayList<String>();
private MusicService.MyBinder binder = null;
Intent intent_service = null;
String path = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
void init(){
list_view_music = (ListView) findViewById(R.id.list_view_music);
getAllMusic();
intent_service = new Intent(MainActivity.this,MusicService.class);
bindService(intent_service, MainActivity.this, Context.BIND_AUTO_CREATE);
list_view_music.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
path = getPathByName(list_name.get(i));
binder.setData(path);
binder.setAllMusic(list_music_pojo);
startService(intent_service);
Intent intent = new Intent(MainActivity.this,MusicPlay.class);
startActivity(intent);
}
});
}
void getAllMusic(){
Cursor cursor = this.getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
null,
null,
null,
MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
list_music_pojo = new ArrayList<MusicPOJO>();
if(cursor.moveToFirst()){
do{
MusicPOJO pojo = new MusicPOJO();
pojo.setName(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)));
pojo.setPath(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)));
list_name.add(pojo.getName());
list_music_pojo.add(pojo);
}while (cursor.moveToNext());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list_name);
list_view_music.setAdapter(adapter);
}
String getPathByName(String name){
for(MusicPOJO pojo : list_music_pojo){
if(name.equals(pojo.getName())){
return pojo.getPath();
}
}
return null;
}
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
binder = (MusicService.MyBinder) iBinder;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
}
MusicService.java
package com.example.administrator.mmusic;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import java.io.IOException;
import java.util.List;
public class MusicService extends Service {
public MediaPlayer mediaPlayer = new MediaPlayer();;
public MyBinder binder = new MyBinder();
List<?> music_list;
String path;
public MusicService() {
}
@Override
public IBinder onBind(Intent intent) {
return new MyBinder();
}
@Override
public void onCreate() {
super.onCreate();
try {
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();
mediaPlayer.setLooping(true);
}catch (Exception e){
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer arg0) {
mediaPlayer.reset();
try {
mediaPlayer.setDataSource(randomPlay());
mediaPlayer.prepare();
mediaPlayer.start();
}catch (Exception e){
e.printStackTrace();
}
}
});
}catch (Exception e){
}
return super.onStartCommand(intent, flags, startId);
}
public class MyBinder extends Binder{
MusicService getService(){
return MusicService.this;
}
public void setData(String data){
MusicService.this.path = data;
}
public void setAllMusic(List<?> music_list){
MusicService.this.music_list = music_list;
}
public boolean isPlay(){
return mediaPlayer.isPlaying();
}
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
String randomPlay(){
int music_position = (int)(Math.random() * music_list.size());
return ((MusicPOJO)(music_list.get(music_position))).getPath();
}
}
布局文件:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context="com.example.administrator.mmusic.MainActivity">
<ListView
android:id="@+id/list_view_music"
android:layout_width="match_parent"
android:layout_height="match_parent"></ListView>
</android.support.constraint.ConstraintLayout>
github地址 |