0910Android音樂播放器

原理

實現功能

  • 點擊音樂列表中的音樂播放
  • 暫停播放開始播放(包括暫停以後拖動進度條到其他位置再播放)
  • 拖動音樂進度條,音樂從拖動結束位置播放
  • 上一首下一首音樂

流程圖

這裏寫圖片描述 

原理  

  利用了mediaplayer,廣播,服務,listView完成了整體任務。
  在主函數中獲得音樂地址,通過listView中的item點擊事件打開服務,將音樂路徑和名稱傳到服務中。然後在服務中打開音樂,將音樂的播放時間和音樂名稱通過廣播傳到主線程中,開啓服務中的線程將音樂的實時時間(耗時操作)傳到主線程中。
  在主線程中註冊廣播,新建廣播接收器的實例。廣播接收器通過發送廣播時type類型來區別音樂的播放時間和音樂的實時時間,並依此設置textview和seekbar。
  跳轉功能通過在服務中MediaPlayer的seekTo來實現。
  暫停播放設置點擊事件,通過一個flag,使暫停和播放通過點擊交替執行。設置點擊具體功能也是在服務中進行,點一下MediaPlayer暫停pause(),再點一下start()。
  音樂的上一首下一首,在主線程中控制,在服務中執行打開音樂的代碼塊。主線程中通過定義一個全局變量將listView中的position獲取。在設置上下首音樂的點擊事件中打開播放音樂的服務,並且通過position來設置播放音樂。

功能具體實現

主線程中註冊廣播,建立廣播接收器實例。獲得音樂,打開音樂適配器。

獲得音樂

//        獲得所有的歌曲
        final File music = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
        musics = music.listFiles();

打開音樂適配器

//          添加到listView中
        final LayoutInflater inflater = getLayoutInflater();
        MusicAdapter musicAdapter = new MusicAdapter(inflater, musics);
        mListView.setAdapter(musicAdapter);

音樂適配器中獲取歌曲的名字,作者,圖片

  public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder vh=null;
        if(convertView==null){
            vh=new ViewHolder();
            convertView=mInflater.inflate(R.layout.listview_item,null);
            vh.musicName = (TextView) convertView.findViewById(R.id.textview_music_name);
            vh.musicAuther = (TextView) convertView.findViewById(R.id.tv_music_auther);
            vh.img= (ImageView) convertView.findViewById(R.id.img);
            convertView.setTag(vh);
        }
        vh= (ViewHolder) convertView.getTag();
//        設置音樂名稱
        vh.musicName.setText(musics[position].getName());

//      獲取作家
        MediaMetadataRetriever mmr=new MediaMetadataRetriever();
        mmr.setDataSource(musics[position].getAbsolutePath());
        String auther=mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
//        判斷作者是否爲空
        if(auther!=null){
            vh.musicAuther.setText(auther);
        }else {
            vh.musicAuther.setText("<未知>");
        }

//        獲得圖片
        byte[] image=mmr.getEmbeddedPicture();
        if(image!=null){
            Bitmap bitmap= BitmapFactory.decodeByteArray(image,0,image.length);
            vh.img.setImageBitmap(bitmap);
        }else{
            vh.img.setImageResource(R.mipmap.ic_launcher);
        }
        return convertView;
    }
    class ViewHolder{
        TextView musicName;
        TextView musicAuther;
        ImageView img;
    }

動態註冊廣播

//          註冊廣播
        myBroad = new MyBroadCastService();
        IntentFilter filter = new IntentFilter();
        filter.addAction(MUSIC_TIME);
        registerReceiver(myBroad, filter);

  註銷廣播

//    動態註冊註銷廣播
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myBroad);
    }

新建廣播實例

    //    在活動中接受廣播以便設置UI參數
    class MyBroadCastService extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            int type = intent.getIntExtra("type", 0);
            switch (type) {
                case 0:
                    int time = intent.getIntExtra("time", 0);
                    mSeekBar.setMax(time);
                    Date date1=new Date(time);
                    SimpleDateFormat format1=new SimpleDateFormat("mm:ss");
                    String s1=format1.format(date1);
                    mTextViewAllTime.setText(s1);
                    break;
                case 1:
                    int time1 = intent.getIntExtra("time", 0);
                    mSeekBar.setProgress(time1);
                    Date date=new Date(time1);
                    SimpleDateFormat format=new SimpleDateFormat("mm:ss");
                    String s=format.format(date);
                    mTextViewCurrentTime.setText(s);
                    break;
            }
        }
    }

打開音樂

主線程中設置點擊事件

//        打開服務,在服務中打開音樂
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getApplicationContext(), MyService.class);
//                將點擊位置的音樂路徑傳到服務中
                intent.putExtra("musicPath", musics[position].getAbsolutePath());
                intent.putExtra("musicName", musics[position].getName());
                intent.putExtra("type",Config.MUSIC_CLICK_START);
                startService(intent);
//                用於設置下一首上一首音樂
                mPosition =position;
            }
        });

服務中實現打開音樂

 private void startMusic(Intent intent) {
        String musicPath = intent.getStringExtra("musicPath");
        musicName= intent.getStringExtra("musicName");
//        防止多個歌曲重複
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
        }
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(musicPath);
            mediaPlayer.prepare();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                    int allTime = mediaPlayer.getDuration();
//                   發送廣播將時間參數送過去
                    Intent intent1 = new Intent(MainActivity.MUSIC_TIME);
                    intent1.putExtra("type", 0);
                    intent1.putExtra("time", allTime);
                    intent1.putExtra("name",musicName);
                    sendBroadcast(intent1);
//                    服務中不能進行耗時操作,啓動一個線程來傳遞音樂進度條(耗時操作)
                    MySeekBar seekBar = new MySeekBar();
                    seekBar.start();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

服務其中打開的線程

  class MySeekBar extends Thread {
        @Override
        public void run() {
//            super.run();
            while (mediaPlayer.isPlaying()) {
                int now = mediaPlayer.getCurrentPosition();
                Intent intent1 = new Intent(MainActivity.MUSIC_TIME);
                intent1.putExtra("type", 1);
                intent1.putExtra("time", now);
                sendBroadcast(intent1);
                try {
//                    休眠一秒
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

這裏寫圖片描述

實現音樂隨進度條播放

主線程中設置點擊事件

//        設置音樂隨着seekbar的跳轉
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                Intent intent=new Intent(getApplicationContext(),MyService.class);
                intent.putExtra("type", Config.MUSIC_SEEK);
                intent.putExtra("progress",seekBar.getProgress());
                startService(intent);
            }
        });

服務中實現音樂隨進度條播放

  private void seekToProgress(Intent intent) {
        int progress = intent.getIntExtra("progress", 0);
//                歌曲跳轉到progress的位置後保持原來狀態
        mediaPlayer.seekTo(progress);
    }

這裏寫圖片描述

實現音樂暫停

主線程中設置點擊事件

 mBtnPauseMusic.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Intent intent=new Intent(getApplicationContext(),MyService.class);
                intent.putExtra("flag", flag);
                intent.putExtra("type", Config.MUSIC_BUTTON_PAUSE);
                startService(intent);
                flag=!flag;
            }
        });

服務中實現音樂暫停

 private void pauseMusic(Intent intent) {
        boolean flag = intent.getBooleanExtra("flag", true);
        if (!flag) {
//                    此時線程關閉了
            mediaPlayer.pause();
        } else {
//                  跳轉到暫停後滑動到的位置
            int keepOn = mediaPlayer.getCurrentPosition();
            mediaPlayer.seekTo(keepOn);
            mediaPlayer.start();
//                    再次打開線程
            MySeekBar seekBar = new MySeekBar();
            seekBar.start();
        }
    }

這裏寫圖片描述

實現下一首音樂

主線程中設置點擊事件

//      設置下一首音樂
        mBtnNextMusic.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                不是最後一首音樂時mPosition才+1
                if(mPosition!=musics.length-1){
                    mPosition++;
                }
                Intent intent = new Intent(getApplicationContext(), MyService.class);
//                將點擊位置的音樂路徑傳到服務中
                intent.putExtra("musicPath", musics[mPosition].getAbsolutePath());
                intent.putExtra("musicName", musics[mPosition].getName());
                intent.putExtra("type", Config.MUSIC_NEXT);
                startService(intent);

            }
        });

服務中實現下一首音樂

  在服務中調用打開音樂方法startMusic(intent)

這裏寫圖片描述

實現上一首音樂

主線程中設置點擊事件

//        設置上一首音樂
        mBtnBeforeMusic.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                      不是第一首音樂時mPosition才-1
                if(mPosition!=0){
                    mPosition--;
                }
                Intent intent = new Intent(getApplicationContext(), MyService.class);
//                將點擊位置的音樂路徑傳到服務中
                intent.putExtra("musicPath", musics[mPosition].getAbsolutePath());
                intent.putExtra("musicName", musics[mPosition].getName());
                intent.putExtra("type", Config.MUSIC_PREVIOUS);
                startService(intent);
            }
        });

服務中實現上一首音樂

  在服務中調用打開音樂方法startMusic(intent)

這裏寫圖片描述

全部代碼

佈局

<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:gravity="center"
    android:orientation="vertical"

    tools:context=".MainActivity">

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:cacheColorHint="#00000000"
        android:background="#ffffff"
        android:divider="@null"
        android:layout_weight="1"></ListView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/background"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center">

            <TextView
                android:id="@+id/textview_current_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:text="00:00" />

            <TextView
                android:id="@+id/textview_all_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_margin="5dp"
                android:text="00:00" />

        </RelativeLayout>

        <SeekBar
            android:id="@+id/seekbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:gravity="center">

            <CheckBox
                android:id="@+id/btn_brfore_music"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/previous_music"
                android:button="@null" />

            <CheckBox
                android:id="@+id/btn_pause_music"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="30dp"
                android:layout_marginRight="30dp"
                android:background="@drawable/start_pause_press"
                android:button="@null" />

            <CheckBox
                android:id="@+id/btn_next_music"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/next_music"
                android:button="@null" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

這裏寫圖片描述

ListViewitem佈局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
android:gravity="center_vertical"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/img"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_margin="10dp"
        android:src="@mipmap/ic_launcher"/>
<TextView
    android:id="@+id/textview_music_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:text="音樂名稱"/>
    <TextView
        android:id="@+id/tv_music_auther"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="作家"
        android:layout_margin="10dp"
        />

</LinearLayout>

這裏寫圖片描述

主線程

package com.example.laowang.mymediaplayer;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Environment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.laowang.mymediaplayer.adapter.Config;
import com.example.laowang.mymediaplayer.adapter.MusicAdapter;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends Activity{
    private CheckBox mBtnBeforeMusic;
    private CheckBox mBtnPauseMusic;
    private CheckBox mBtnNextMusic;
    private SeekBar mSeekBar;
    private ListView mListView;
    private TextView mTextViewAllTime;
    private TextView mTextViewCurrentTime;
    private TextView mTextViewMusicName;
    private MyBroadCastService myBroad;
    private int mPosition;
    private File[] musics;
    private boolean flag;
    public static final String MUSIC_TIME = "com.laowang.music";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        mBtnBeforeMusic = (CheckBox) findViewById(R.id.btn_brfore_music);
        mBtnNextMusic = (CheckBox) findViewById(R.id.btn_next_music);
        mBtnPauseMusic = (CheckBox) findViewById(R.id.btn_pause_music);
        mSeekBar = (SeekBar) findViewById(R.id.seekbar);
        mListView = (ListView) findViewById(R.id.listview);
        mTextViewAllTime = (TextView) findViewById(R.id.textview_all_time);
        mTextViewCurrentTime = (TextView) findViewById(R.id.textview_current_time);
        mTextViewMusicName = (TextView) findViewById(R.id.textview_music_name);

//        獲得所有的歌曲
        final File music = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
        musics = music.listFiles();
        for (File item:musics){
            Log.d("歌曲的位置", "→"+item);
        }
//          添加到listView中
        final LayoutInflater inflater = getLayoutInflater();
        MusicAdapter musicAdapter = new MusicAdapter(inflater, musics);
        mListView.setAdapter(musicAdapter);
//          註冊廣播
        myBroad = new MyBroadCastService();
        IntentFilter filter = new IntentFilter();
        filter.addAction(MUSIC_TIME);
        registerReceiver(myBroad, filter);

//      設置下一首音樂
        mBtnNextMusic.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                不是最後一首音樂時mPosition才+1
                if(mPosition!=musics.length-1){
                    mPosition++;
                }
                Intent intent = new Intent(getApplicationContext(), MyService.class);
//                將點擊位置的音樂路徑傳到服務中
                intent.putExtra("musicPath", musics[mPosition].getAbsolutePath());
                intent.putExtra("musicName", musics[mPosition].getName());
                intent.putExtra("type", Config.MUSIC_NEXT);
                startService(intent);

            }
        });

//        設置上一首音樂
        mBtnBeforeMusic.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                      不是第一首音樂時mPosition才-1
                if(mPosition!=0){
                    mPosition--;
                }
                Intent intent = new Intent(getApplicationContext(), MyService.class);
//                將點擊位置的音樂路徑傳到服務中
                intent.putExtra("musicPath", musics[mPosition].getAbsolutePath());
                intent.putExtra("musicName", musics[mPosition].getName());
                intent.putExtra("type", Config.MUSIC_PREVIOUS);
                startService(intent);
            }
        });

//      設置音樂暫停開始
        mBtnPauseMusic.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Intent intent=new Intent(getApplicationContext(),MyService.class);
                intent.putExtra("flag", flag);
                intent.putExtra("type", Config.MUSIC_BUTTON_PAUSE);
                startService(intent);
                flag=!flag;
            }
        });

//        打開服務,在服務中打開音樂
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getApplicationContext(), MyService.class);
//                將點擊位置的音樂路徑傳到服務中
                intent.putExtra("musicPath", musics[position].getAbsolutePath());
                intent.putExtra("musicName", musics[position].getName());
                intent.putExtra("type",Config.MUSIC_CLICK_START);
                startService(intent);
//                用於設置下一首上一首音樂
                mPosition =position;
            }
        });

//        設置音樂隨着seekbar的跳轉
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                Intent intent=new Intent(getApplicationContext(),MyService.class);
                intent.putExtra("type", Config.MUSIC_SEEK);
                intent.putExtra("progress",seekBar.getProgress());
                startService(intent);
            }
        });
    }

//    動態註冊註銷廣播

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myBroad);
    }

    //    在活動中接受廣播以便設置UI參數
    class MyBroadCastService extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            int type = intent.getIntExtra("type", 0);
            switch (type) {
                case 0:
                    int time = intent.getIntExtra("time", 0);
                    mSeekBar.setMax(time);
                    Date date1=new Date(time);
                    SimpleDateFormat format1=new SimpleDateFormat("mm:ss");
                    String s1=format1.format(date1);
                    mTextViewAllTime.setText(s1);
                    String name=intent.getStringExtra("name");
                    mTextViewMusicName.setText(name);
                    break;
                case 1:
                    int time1 = intent.getIntExtra("time", 0);
                    mSeekBar.setProgress(time1);
                    Date date=new Date(time1);
                    SimpleDateFormat format=new SimpleDateFormat("mm:ss");
                    String s=format.format(date);
                    mTextViewCurrentTime.setText(s);
                    break;
            }
        }
    }
}

適配器

package com.example.laowang.mymediaplayer.adapter;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.laowang.mymediaplayer.R;

import java.io.File;

/**
 * Created by Administrator on 2015/9/10.
 */
public class MusicAdapter extends BaseAdapter {
    private LayoutInflater mInflater;
    private File[] musics;

    public MusicAdapter(LayoutInflater mInflater, File[] musics) {
        this.mInflater = mInflater;
        this.musics = musics;
    }

    @Override
    public int getCount() {
        return musics.length;
    }

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder vh=null;
        if(convertView==null){
            vh=new ViewHolder();
            convertView=mInflater.inflate(R.layout.listview_item,null);
            vh.musicName = (TextView) convertView.findViewById(R.id.textview_music_name);
            vh.musicAuther = (TextView) convertView.findViewById(R.id.tv_music_auther);
            vh.img= (ImageView) convertView.findViewById(R.id.img);
            convertView.setTag(vh);
        }
        vh= (ViewHolder) convertView.getTag();
//        設置音樂名稱
        vh.musicName.setText(musics[position].getName());

//      獲取作家
        MediaMetadataRetriever mmr=new MediaMetadataRetriever();
        mmr.setDataSource(musics[position].getAbsolutePath());
        String auther=mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
//        判斷作者是否爲空
        if(auther!=null){
            vh.musicAuther.setText(auther);
        }else {
            vh.musicAuther.setText("<未知>");
        }

//        獲得圖片
        byte[] image=mmr.getEmbeddedPicture();
        if(image!=null){
            Bitmap bitmap= BitmapFactory.decodeByteArray(image,0,image.length);
            vh.img.setImageBitmap(bitmap);
        }else{
            vh.img.setImageResource(R.mipmap.ic_launcher);
        }
        return convertView;
    }
    class ViewHolder{
        TextView musicName;
        TextView musicAuther;
        ImageView img;
    }
}

服務

package com.example.laowang.mymediaplayer;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.example.laowang.mymediaplayer.adapter.Config;

import java.io.IOException;

/**
 * Created by Administrator on 2015/9/10.
 */
public class MyService extends Service {
    private MediaPlayer mediaPlayer;
    private boolean flag;
    private String musicName;

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

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        int type = intent.getIntExtra("type", Config.MUSIC_CLICK_START);
        switch (type) {
            case Config.MUSIC_CLICK_START:
                startMusic(intent);
                break;
            case Config.MUSIC_SEEK:
                seekToProgress(intent);
                break;
            case Config.MUSIC_BUTTON_PAUSE:
                pauseMusic(intent);
                break;
            case Config.MUSIC_NEXT:
                startMusic(intent);
                break;
            case Config.MUSIC_PREVIOUS:
                startMusic(intent);
                break;
            default:
                break;
        }


        return super.onStartCommand(intent, flags, startId);
    }


    private void seekToProgress(Intent intent) {
        int progress = intent.getIntExtra("progress", 0);
//                歌曲跳轉到progress的位置後保持原來狀態
        mediaPlayer.seekTo(progress);
    }

    private void pauseMusic(Intent intent) {
        boolean flag = intent.getBooleanExtra("flag", true);
        if (!flag) {
//                    此時線程關閉了
            mediaPlayer.pause();
        } else {
//                  跳轉到暫停後滑動到的位置
            int keepOn = mediaPlayer.getCurrentPosition();
            mediaPlayer.seekTo(keepOn);
            mediaPlayer.start();
//                    再次打開線程
            MySeekBar seekBar = new MySeekBar();
            seekBar.start();
        }
    }

    private void startMusic(Intent intent) {
        String musicPath = intent.getStringExtra("musicPath");
        musicName= intent.getStringExtra("musicName");
//        防止多個歌曲重複
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
        }
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(musicPath);
            mediaPlayer.prepare();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                    int allTime = mediaPlayer.getDuration();
//                   發送廣播將時間參數送過去
                    Intent intent1 = new Intent(MainActivity.MUSIC_TIME);
                    intent1.putExtra("type", 0);
                    intent1.putExtra("time", allTime);
                    intent1.putExtra("name",musicName);
                    sendBroadcast(intent1);
//                    服務中不能進行耗時操作,啓動一個線程來傳遞音樂進度條(耗時操作)
                    MySeekBar seekBar = new MySeekBar();
                    seekBar.start();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    class MySeekBar extends Thread {
        @Override
        public void run() {
//            super.run();
            while (mediaPlayer.isPlaying()) {
                int now = mediaPlayer.getCurrentPosition();
                Intent intent1 = new Intent(MainActivity.MUSIC_TIME);
                intent1.putExtra("type", 1);
                intent1.putExtra("time", now);
                sendBroadcast(intent1);
                try {
//                    休眠一秒
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

存放靜態常量的類

package com.example.laowang.mymediaplayer.adapter;

/**
 * Created by Administrator on 2015/9/10.
 */
public class Config {
    public static final int MUSIC_CLICK_START =1;
    public static final int MUSIC_SEEK=0;
    public static final int MUSIC_BUTTON_PAUSE =2;
    public static final int MUSIC_BUTTON_START=3;
    public static final int MUSIC_NEXT=5;
    public static final int MUSIC_PREVIOUS =4;


}

AndroidMainFest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.laowang.mymediaplayer" >
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".MyService"/>
    </application>

</manifest>
發佈了56 篇原創文章 · 獲贊 1 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章