利用Service实现播放手机上的MP3音乐(MediaPlayer)

在Activity界面上操作播放暂停,然后在后台运行Service,达到播放音乐的目的。

MidiaPlayer的工作流程图:




在布局中自定义的滚动条,图片资源在:http://download.csdn.net/detail/zhangli_/9412080

为了达到合适的效果,建议progress_bar_n.9.png和progress_bar_p.9.png两张图片放在drawable-xxhdpi下;player_progress_thumb.png图片放在drawable-xhdpi下。

这是滚动条布局xml文件,seekbar_progressdrawable_selector.xml:

<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@android:id/background"
        android:drawable="@drawable/progress_bar_n">
    </item>
    <item android:id="@android:id/progress">
        <clip>
            <nine-patch android:src="@drawable/progress_bar_p"/>
        </clip>
    </item>
</layer-list>

activity_music_layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.zhangli.myapplication.MusicActivity">

    <LinearLayout
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/mp3_start_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="播放"
            />

        <Button
            android:id="@+id/mp3_stop_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="停止"
            />
    </LinearLayout>

    <RelativeLayout
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/start_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="10dp"
            android:text="00:00"/>

        <TextView
            android:id="@+id/stop_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginRight="10dp"
            android:text="00:00"/>

        <SeekBar
            android:id="@+id/seebar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:progressDrawable="@drawable/seekbar_progressdrawable_selector"
            android:thumb="@drawable/player_progress_thumb"
            android:layout_toLeftOf="@id/stop_time"
            android:layout_toRightOf="@id/start_time"/>

    </RelativeLayout>
</LinearLayout>

效果:只有播放/暂停和停止的功能,进度条可拖动播放。



服务MusicService:

package com.zhangli.myapplication;

import android.app.IntentService;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;

import java.io.IOException;

public class MusicService extends IntentService {

    private static int palyTime;
    private static int allTime;
    private static String mp3path;

    private static MediaPlayer mediaPlayer = new MediaPlayer();
    boolean b = true;

    public MusicService() {
        super("MusicService");

    }
    @Override
    public void onCreate() {
        super.onCreate();
        MyGetTimeClass.inintMusic();
        Log.e("tag", "进入预播放阶段");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        allTime = mediaPlayer.getDuration();
        Log.e("tag", "开始播放阶段");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        while (b) {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                //得到当时的音乐时间
                palyTime = mediaPlayer.getCurrentPosition();
            }else{
                palyTime=0;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        b = false;
        mediaPlayer.reset();
        mediaPlayer = null;
    }

    private interface GetTime {
        //正在播放的音乐时间
        int getPalyTime();
        //总的音乐时间
        int getAllTime();
        //暂停
        void pausedMusic();
        //是否播放
        boolean isPalying();
        //是否是歌曲
        boolean isMusic();
        //播放音乐
        void palyMusic();
        //关联音乐到滚动条上,即拉动滚动条,音乐播放滚动条当前位置
        void seekto(int i);
        //结束播放
        void myRelease();
        //开始进入播放初始化
        void myReset();
    }

    public static class MyGetTimeClass extends Binder implements GetTime {
        public static void inintMusic() {
            //在手机根目录下的Music文件夹"对不起谢谢.mp3"
            mp3path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath() + "/对不起谢谢.mp3";
            Log.e("tag", "mp3path" + mp3path);
            try {
                mediaPlayer.setDataSource(mp3path);
                mediaPlayer.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public int getPalyTime() {
            return palyTime;
        }

        @Override
        public int getAllTime() {
            return allTime;
        }

        @Override
        public void pausedMusic() {
            mediaPlayer.pause();
        }

        @Override
        public boolean isPalying() {
            if (mediaPlayer.isPlaying()) {
                return true;
            } else {
                return false;
            }
        }

        @Override
        public boolean isMusic() {
            if (mp3path != null) {
                return true;
            } else {
                return false;
            }
        }

        @Override
        public void palyMusic() {
            mediaPlayer.start();
        }

        @Override
        public void seekto(int i) {
            mediaPlayer.seekTo(i);
        }

        @Override
        public void myRelease() {
            mediaPlayer.release();
        }

        @Override
        public void myReset() {
            mediaPlayer.reset();
        }
    }

    public MyGetTimeClass mgetTimeClass = new MyGetTimeClass();

    @Override
    public IBinder onBind(Intent intent) {
        return mgetTimeClass;
    }
}

MusicActivity:

一创建界面,那么就开启服务,直到销毁。

package com.zhangli.myapplication;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;

public class MusicActivity extends Activity implements View.OnClickListener {
    private TextView startMusicTimeTex, stopMusicTimeTex;
    private Button palyMusicBtn, stopMusicBtn;
    private SeekBar seekBar;
    private MusicService.MyGetTimeClass myGetTimeClass;
    private SimpleDateFormat format = new SimpleDateFormat("mm:ss");
    private Handler mHandler = new Handler();

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myGetTimeClass = (MusicService.MyGetTimeClass) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Toast.makeText(getApplication(),"服务出错",Toast.LENGTH_SHORT).show();
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_layout);

        startMusicTimeTex = (TextView) findViewById(R.id.start_time);
        stopMusicTimeTex = (TextView) findViewById(R.id.stop_time);
        palyMusicBtn = (Button) findViewById(R.id.mp3_start_btn);
        stopMusicBtn = (Button) findViewById(R.id.mp3_stop_btn);
        seekBar = (SeekBar) findViewById(R.id.seebar);

        palyMusicBtn.setOnClickListener(this);
        stopMusicBtn.setOnClickListener(this);
        seekBar.setOnClickListener(this);

        //进度条的状态
        mySeekBar();

        //开启服务 绑定服务
        Intent intent= new Intent(this, MusicService.class);
        startService(intent);
        bindService(intent, connection, BIND_AUTO_CREATE);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mp3_start_btn:
                stopMusicTimeTex.setText(format.format(myGetTimeClass.getAllTime()));
                seekBar.setMax(myGetTimeClass.getAllTime());
                Log.e("tag", "stopMusicTimeTex" + format.format(myGetTimeClass.getAllTime()));
                Log.e("tag", "getAllTime" + myGetTimeClass.getAllTime());
                if (myGetTimeClass.isPalying()) {

                    Log.e("tag","进去暂停》》》》》》》");
                    palyMusicBtn.setText("播放");
                    myGetTimeClass.pausedMusic();
                }else {
                    Log.e("tag", "进去播放》》》》》》》");
                    myGetTimeClass.palyMusic();
                    Log.e("tag", "myGetTimeClass.palyMusic();" + myGetTimeClass);
                    palyMusicBtn.setText("暂停");
                    Log.e("tag","settext:"+"暂停");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            while (myGetTimeClass.isPalying()) {
                                if (myGetTimeClass.isMusic()) {
                                    Log.e("tag","myGetTimeClass.isMusic():"+myGetTimeClass.isMusic());
                                    mHandler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            startMusicTimeTex.setText(format.format(myGetTimeClass.getPalyTime()));
                                            Log.e("tag", "format.format(myGetTimeClass.getPalyTime()):" + format.format(myGetTimeClass.getPalyTime()));
                                            seekBar.setProgress(myGetTimeClass.getPalyTime());
                                        }
                                    });
                                    try {
                                        Thread.sleep(1000);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }).start();
                }
                break;
            case R.id.mp3_stop_btn:
                myGetTimeClass.myReset();
                myGetTimeClass.inintMusic();
                startMusicTimeTex.setText(format.format(0));
                seekBar.setProgress(0);
                palyMusicBtn.setText("播放");
                break;
        }
    }
    public void mySeekBar(){
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            int mProgress;
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                Log.e("tag", "onProgressChanged progress :" + progress);
                mProgress = progress;
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                Log.e("tag", "onStartTrackingTouch >>>>> ");
                //暂停
                myGetTimeClass.pausedMusic();
                palyMusicBtn.setText("播放");
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                Log.e("tag", "onStopTrackingTouch >>>>> ");
                myGetTimeClass.seekto(mProgress);
                startMusicTimeTex.setText(format.format(mProgress));
                myGetTimeClass.palyMusic();
                palyMusicBtn.setText("暂停");

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
//        myGetTimeClass.myRelease();
//        myGetTimeClass = null;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值