簡單的Android 音樂播放器實現

環境: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地址

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章