实现一个音乐播放器

1、显示歌曲名,艺人,专辑。页面有mini条包含暂停恢复,上下首按钮,可以显示歌曲信息。
2、点击后启动播放,使用后出通知栏提醒。
3、可以从service拿到播放信息更新ui
4、通知栏效果可以参考常见音乐播放器排版。

public class MusicActivity extends AppCompatActivity implements View.OnClickListener {


    private Button mPrevious,mPlay,mNext,mPause;
    private ComponentName component;

    private MyReceiver receiver;

    private TextView textView;

    private ListView listView;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        receiver=new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.skyl.RECEIVER");
        registerReceiver(receiver,intentFilter);

        setupViews();
    }
    //初始化
    public void setupViews(){
        listView= (ListView) findViewById(R.id.listview);
        component = new ComponentName(this,
                MusicService.class);
        textView= (TextView) findViewById(R.id.textView);
        mPrevious = (Button)findViewById(R.id.previous);
        mPlay = (Button)findViewById(R.id.play);
        mNext = (Button)findViewById(R.id.next);
        mPause = (Button)findViewById(R.id.pause);

        mPrevious.setOnClickListener(this);
        mPlay.setOnClickListener(this);
        mNext.setOnClickListener(this);
        mPause.setOnClickListener(this);
    }

    public void onClick(View v) {
        if(v == mPrevious){
            Intent mIntent = new Intent(MusicService.PREVIOUS_ACTION);
            mIntent.setComponent(component);
            startService(mIntent);
        }else if(v == mPlay){
            Intent mIntent = new Intent(MusicService.PLAY_ACTION);
            mIntent.setComponent(component);
            startService(mIntent);
        }else if(v == mNext){
            Intent mIntent = new Intent(MusicService.NEXT_ACTION);
            mIntent.setComponent(component);
            startService(mIntent);
        }else{
            Intent mIntent = new Intent(MusicService.PAUSE_ACTION);
            mIntent.setComponent(component);
            startService(mIntent);
        }

    }

    public class MyReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            String info =intent.getStringExtra("info");
            textView.setText(info);
            ArrayList<String> musiclist = intent.getStringArrayListExtra("MusitList");
            listView.setAdapter(new ArrayAdapter<String>(MusicActivity.this,android.R.layout.simple_list_item_1,musiclist));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
public class MusicService extends Service {


    String[] mCursorCols = new String[] {
            "audio._id AS _id",
            MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM,
            MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DATA,
            MediaStore.Audio.Media.MIME_TYPE, MediaStore.Audio.Media.ALBUM_ID,
            MediaStore.Audio.Media.ARTIST_ID, MediaStore.Audio.Media.DURATION
    };
    private MediaPlayer mMediaPlayer;
    private Cursor mCursor;
    private int mPlayPosition = 0;
    ArrayList<String> list;


    public static final String PLAY_ACTION = "com.skyl.music.PLAY_ACTION";
    public static final String PAUSE_ACTION = "com.skyl.music.PAUSE_ACTION";
    public static final String NEXT_ACTION = "com.skyl.music.NEXT_ACTION";
    public static final String PREVIOUS_ACTION = "com.skyl.music.PREVIOUS_ACTION";
    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        mMediaPlayer = new MediaPlayer();
        //通过一个URI可以获取所有音频文件默认大于10秒的可以看作是歌
        Uri MUSIC_URL = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        mCursor = getContentResolver().query(MUSIC_URL, mCursorCols, "duration > 10000", null, null);
        list=new ArrayList<>();
//        发送广播更新UI
        while(mCursor.moveToNext()){
            int titleColumn = mCursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
            String titleName=mCursor.getString(titleColumn);
            list.add(titleName);
        }

    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action = intent.getAction();
        if(action.equals(PLAY_ACTION)){
            play();
        }else if(action.equals(PAUSE_ACTION)){
            pause();
        }else if(action.equals(NEXT_ACTION)){
            next();
        }else if(action.equals(PREVIOUS_ACTION)){
            previous();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    //play the music
    public void play() {
        inite();
    }

    //暂停时,结束服务
    public void pause() {
        stopSelf();
    }
    //上一首
    public void previous() {
        if (mPlayPosition == 0) {
            mPlayPosition = mCursor.getCount() - 1;
        } else {
            mPlayPosition--;
        }
        inite();
    }
    //下一首
    public void next() {
        if (mPlayPosition == mCursor.getCount() - 1) {
            mPlayPosition = 0;
        } else {
            mPlayPosition++;
        }
        inite();
    }
    //初始化
    public void inite() {
        mMediaPlayer.reset();
        String dataSource = getDateByPosition(mCursor, mPlayPosition);
        String info = getInfoByPosition(mCursor, mPlayPosition);

        Intent intent =new Intent("com.skyl.RECEIVER");
        intent.putExtra("info",info);
        intent.putStringArrayListExtra("MusitList",list);
        sendBroadcast(intent);

        //开启通知栏
        startForeground(1,onCreateNotifi(info));

        try {
            mMediaPlayer.setDataSource(dataSource);
            mMediaPlayer.prepare();
            mMediaPlayer.start();
        } catch (IllegalArgumentException e1) {
            e1.printStackTrace();
        } catch (IllegalStateException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
    //根据位置来获取歌曲位置
    public String getDateByPosition(Cursor c,int position){
        c.moveToPosition(position);
        int dataColumn = c.getColumnIndex(MediaStore.Audio.Media.DATA);
        String data = c.getString(dataColumn);
        return data;
    }
    //获取当前播放歌曲演唱者、歌名及专辑名
    public String getInfoByPosition(Cursor c,int position){
        c.moveToPosition(position);
        int titleColumn = c.getColumnIndex(MediaStore.Audio.Media.TITLE);
        int artistColumn = c.getColumnIndex(MediaStore.Audio.Media.ARTIST);
        int albumColumn=c.getColumnIndex(MediaStore.Audio.Media.ALBUM);
        String info = "歌手名:"+c.getString(artistColumn)+"  歌曲名:" + c.getString(titleColumn)+"  专辑名:"+c.getString(albumColumn);
        return info;

    }
    //服务结束时释放MediaPlayer
    public void onDestroy() {
        super.onDestroy();
        mMediaPlayer.release();
    }

    //创建通知栏
    public Notification onCreateNotifi(String info){

        RemoteViews remoteViews=new RemoteViews(getPackageName(),R.layout.list_item_notification);
        remoteViews.setTextViewText(R.id.tv_nofitication_singname,info);

        //注册上一首点击事件
        Intent previous =new Intent(this,MusicService.class);
        previous.setAction(PREVIOUS_ACTION);
        PendingIntent previousIntent=PendingIntent.getService(this,200,previous,PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.iv_nofitication_kzhi_previous,
                previousIntent);

        //注册播放事件
        Intent play=new Intent(this,MusicService.class);
        play.setAction(PLAY_ACTION);
        PendingIntent playIntent=PendingIntent.getService(this,200,play,PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.iv_nofitication_kzhi_play,
                playIntent);

        //注册下一首事件
        Intent next=new Intent(this,MusicService.class);
        play.setAction(NEXT_ACTION);
        PendingIntent nextIntent=PendingIntent.getService(this,200,play,PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.iv_nofitication_kzhi_next,
                nextIntent);

        //注册暂停事件
        Intent pause=new Intent(this,MusicService.class);
        play.setAction(PAUSE_ACTION);
        PendingIntent pauseIntent=PendingIntent.getService(this,200,play,PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.iv_nofitication_kzhi_colse,
                pauseIntent);

        Notification notification=new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setTicker(info)
                .setContent(remoteViews)
                .build();
        return notification;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值