使用MediaPlayer+Service完成音乐播放器

使用MediaPlayer+Service完成音乐播放器

1,先把歌曲封装成一个类

package com.example.servicemusic;

public class Song {
    private String title;
    private String artist;
    private int duration;
    private String data;
    private int size;

    public Song(String title, String artist, int duration, String data, int size) {
        this.title = title;
        this.artist = artist;
        this.duration = duration;
        this.data = data;
        this.size = size;
    }

    public Song() {
    }

    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;
    }

    public int getDuration() {
        return duration;
    }

    public void setDuration(int duration) {
        this.duration = duration;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }
}

2,封装查询本地歌曲的工具类

package com.example.servicemusic;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

import java.util.ArrayList;
import java.util.List;

public class Utils {
    private Context context;
    private List<Song> list;

    public Utils(Context context, List<Song> list) {
        this.context = context;
        this.list = list;
    }
    public static List<Song> init(Context context){
        List<Song> list=new ArrayList<>();
        //获取音乐的uri
        Uri uri= MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String[] strings={MediaStore.Audio.Media.TITLE,MediaStore.Audio.Media.ARTIST,MediaStore.Audio.Media.DURATION,MediaStore.Audio.Media.DATA,MediaStore.Audio.Media.SIZE};
        ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = contentResolver.query(uri, strings, null, null, null);
        while (cursor.moveToNext()){
        //获取音乐的歌名,作者,时长,地址
            String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
            int duration = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
            String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
            int size = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE));
            Song song = new Song(title,artist,duration,data,size);
            list.add(song);
        }
        cursor.close();
        return list;
    }
}

3 ,封装一个adapter类

package com.example.servicemusic;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.List;

public class Myadpater extends BaseAdapter {
    private Context context;
    private List<Song> list;

    public Myadpater(Context context, List<Song> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Viewholder viewholder;
        if (convertView==null){
            convertView = LayoutInflater.from(context).inflate(R.layout.layout, null);
            viewholder=new Viewholder();
            viewholder.title=convertView.findViewById(R.id.titleid);
            viewholder.artist = convertView.findViewById(R.id.artistid);
            viewholder.duration=convertView.findViewById(R.id.durationid);
            convertView.setTag(viewholder);
        }else {
            viewholder = (Viewholder) convertView.getTag();
        }
        viewholder.title.setText(list.get(position).getTitle());
        viewholder.artist.setText(list.get(position).getArtist());
        int time = list.get(position).getDuration();
        String s = formatTime(time);
        viewholder.duration.setText(s);
        return convertView;
    }
    class Viewholder{
        TextView title;
        TextView artist;
        TextView duration;
    }
    //时长转化为分钟:秒钟
    public static String formatTime(int time) {
        if (time / 1000 % 60 < 10) {
            return time / 1000 / 60 + ":0" + time / 1000 % 60;
        } else {
            return time / 1000 / 60 + ":" + time / 1000 % 60;
        }
    }
}

4, adapter中的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_weight="1"
        android:layout_width="0dp"
        android:orientation="vertical"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/titleid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="我是歌名"
            android:layout_margin="10dp"
            />
        <TextView
            android:id="@+id/artistid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="我是歌手"
            android:layout_margin="10dp"
            />
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="78dp"
        android:layout_weight="0.5"
        android:gravity="center">

        <TextView
            android:id="@+id/durationid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:text="我是时长" />
    </LinearLayout>
</LinearLayout>

5,服务中的所有代码

package com.example.servicemusic;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;

import java.io.IOException;
import java.util.List;

public class MyService extends Service {
    private MediaPlayer mediaPlayer;
    private List<Song> list;
    private int index;
    public MyService() {
    }
    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer=new MediaPlayer();
        list=Utils.init(this);
    }
    @Override
    public IBinder onBind(Intent intent) {
        return new Musicbinder();
    }
    //中间人
    public class Musicbinder extends Binder{
        public void callPlay(int posation){
            playsong(posation);
            index=posation;
        }
        public void  callPause(){
            pause();
        }
        public void  callplaynextsong(){
            if (++index>list.size()-1){
                index=0;
            }
            playsong(index);
        }
        public void  callrestart(){
            restart();
        }
        public void callbacksong(){
            if (--index<0){
                index=0;
            }
           playsong(index);
        }
    }

    private void restart(){
        mediaPlayer.start();
    }


    private void  pause(){
        if (mediaPlayer.isPlaying()){
            mediaPlayer.pause();
        }
    }


    //播放歌曲
    private void playsong(int position){
        if (mediaPlayer.isPlaying()){
            mediaPlayer.stop();
        }
        //重置
        mediaPlayer.reset();
        //取到点击歌曲文件的位置
        Song song = list.get(position);
        try {
            mediaPlayer.setDataSource(song.getData());
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

6 Activity中的布局.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".MainActivity">
    <ListView
        android:id="@+id/listid"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>

    <LinearLayout
        android:gravity="center"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/continueid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="继续播放"
            />
        <Button
            android:id="@+id/stopid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="暂停播放"
            />
        <Button
            android:id="@+id/backid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="上一首"
            />
        <Button
            android:id="@+id/nextid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="下一首"
            />
    </LinearLayout>
</RelativeLayout>

7 Activity中的代码

package com.example.servicemusic;

import android.Manifest;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private ListView listid;
    private Button continueid;
    private Button stopid;
    private Button backid;
    private Button nextid;
    private List<Song> list;
    private Myadpater myadpater;
    private int index;

    private ServiceConnection connection;
    private MyService.Musicbinder biner;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewinit();
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},101);
        }
        listid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                  biner.callPlay(position);
            }
        });

        Intent intent = new Intent(this, MyService.class);
        //1.启动
        startService(intent);

        connection =new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                biner =(MyService.Musicbinder)service;
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };
        //2.绑定
        bindService(intent,connection, Service.BIND_AUTO_CREATE);

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode==101&&grantResults[0]== PackageManager.PERMISSION_GRANTED){
            List<Song> init = Utils.init(this);
            myadpater = new Myadpater(this, init);
            listid.setAdapter(myadpater);
        }
    }

    private void viewinit() {
        listid = (ListView) findViewById(R.id.listid);
        continueid = (Button) findViewById(R.id.continueid);
        continueid.setOnClickListener(this);
        stopid = (Button) findViewById(R.id.stopid);
        stopid.setOnClickListener(this);
        backid = (Button) findViewById(R.id.backid);
        backid.setOnClickListener(this);
        nextid = (Button) findViewById(R.id.nextid);
        nextid.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id){
            case R.id.stopid:
                biner.callPause();
            break;
            case R.id.continueid:
                biner.callrestart();
                break;
            case R.id.nextid:
                biner.callplaynextsong();
                break;
            case R.id.backid:
                biner.callbacksong();
                break;
        }

    }
}
上一篇:Spring------自动化装配Bean(三)


下一篇:Android MediaRecorder录制播放音频