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

使用MediaPlayer+Service完成音乐播放器,第1张

概述使用MediaPlayer+Service完成音乐播放器1,先把歌曲封装成一个类packagecom.example.servicemusic;publicclassSong{privateStringtitle;privateStringartist;privateintduration;privateStringdata;privateintsize;public 使用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;    }}@H_419_11@

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

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

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>@H_419_11@

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();        }    }}@H_419_11@

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>@H_419_11@

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;        }    }}@H_419_11@
总结

以上是内存溢出为你收集整理的使用MediaPlayer+Service完成音乐播放器全部内容,希望文章能够帮你解决使用MediaPlayer+Service完成音乐播放器所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1113863.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-29
下一篇 2022-05-29

发表评论

登录后才能评论

评论列表(0条)