MediaPlayer 实现播放,暂停,续播等功能

废话不多说,直接贴代码:

主代码:直接在主文件中写了功能,一般写在Service里面,这里只是个测试Demo

package com.example.androidmediaplayerdemos;

import java.io.IOException;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.Resources;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener,OnCompletionListener{

    private static final String TAG = "Main";

    private static boolean isBluetooth = false;

    private static MediaPlayer mp = null;

    private static MediaPlayer mpn = null;

    private static MediaPlayer mpnb = null;

    private static AudioManager mAudioManager;

    private static AssetFileDescriptor afd;
    private static Resources res;

    private static int mCurrentVolume;
    private static int mCurrentSysVolume;

    private Button mStart;
    private Button mPause;
    private Button mStop;
    private Button mRestart;
    
    private Button mSeek;
    
    private Button mInit;
    
    private static Context mContext;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        mContext=this;
        
        mAudioManager = (AudioManager) this
                .getSystemService(Context.AUDIO_SERVICE);
        
        
        
        mStart=(Button)findViewById(R.id.player);
        mStart.setOnClickListener(this);
        
        mPause=(Button)findViewById(R.id.pause);
        mPause.setOnClickListener(this);
        
        mStop=(Button)findViewById(R.id.stop);
        mStop.setOnClickListener(this);
        
        mRestart=(Button)findViewById(R.id.restart);
        mRestart.setOnClickListener(this);
        
        mSeek=(Button)findViewById(R.id.seek);
        mSeek.setOnClickListener(this);
        
        mInit=(Button)findViewById(R.id.init);
        mInit.setOnClickListener(this);
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    // notification
        public void InitPlayNotif(Context context, int id) throws IOException {

            stopNotif();
            mpn = new MediaPlayer();
            mAudioManager = (AudioManager) context
                    .getSystemService(context.AUDIO_SERVICE);

            try {

//                mpn.setDataSource(context, ringtoneUri);
                
                res = context.getResources();
                afd = res.openRawResourceFd(R.raw.shanhuhai);

                mpn.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),
                        afd.getLength());

            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                // e.printStackTrace();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                // e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                // e.printStackTrace();
            }

            /*
             * mAudioManager.setSpeakerphoneOn(false);
            mAudioManager.setRouting(AudioManager.MODE_NORMAL, AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL);
            mAudioManager.setMode(AudioManager.MODE_IN_CALL);
            
            mpn.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
            
            mCurrentVolume = mAudioManager
                    .getStreamVolume(AudioManager.STREAM_MUSIC);
                    */

            Log.i(TAG, "notification volume : " + mCurrentVolume);

            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 5, 0);

            try {
                mpn.prepare();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                // e.printStackTrace();
            }

//            mpn.start();
            
            mpn.setOnSeekCompleteListener(new OnSeekCompleteListener(){

                @Override
                public void onSeekComplete(MediaPlayer arg0) {
                    // TODO Auto-generated method stub
                    Toast.makeText(mContext, "play completely !", Toast.LENGTH_SHORT).show();
                    
                }
                
            });
            

        }

        public static void stopNotif() {

            try {
                if (mpn != null) {
                    mpn.stop();
                    mpn.release();
                    mpn = null;
                }
            } catch (Exception e) {

            }

        }

        private void startPlayer(){
            
            if(mpn==null){
                return;
            }
            
            try {
                try {
                    mpn.prepare();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                // e.printStackTrace();
            }

            mpn.start();
            
        }
        
        private void pausePlayer(){
            
            if(mpn==null){
                return;
            }
            
            mpn.pause();
            
        }
        
        private void restartPlayer(){
            
            if(mpn==null){
                return;
            }
            
            mpn.start();
            
        }
        
        private void seekPlayer(){
            
            if(mpn==null){
                return;
            }
            
            mpn.seekTo(1000*60);
            
            mpn.setOnSeekCompleteListener(new OnSeekCompleteListener(){

                @Override
                public void onSeekComplete(MediaPlayer arg0) {
                    // TODO Auto-generated method stub
                    
                    mpn.start();
                    
                }
                
            });
            
        }
        
        private void stopPlayer(){
            
            if(mpn==null){
                return;
            }
            
            stopNotif();
            
        }
        
        private void initPlayer(){
            
            try {
                InitPlayNotif(this,0);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
        
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            int id=arg0.getId();
            
            switch(id){
            case R.id.player:
                startPlayer();
                break;
            case R.id.pause:
                pausePlayer();
                break;
            case R.id.restart:
                restartPlayer();
                break;
            case R.id.stop:
                stopPlayer();
                break;
            case R.id.seek:
                seekPlayer();
                break;
            case R.id.init:
                initPlayer();
                break;
                default :
                    break;
            }
            
            
        }

        @Override
        public void onCompletion(MediaPlayer arg0) {
            // TODO Auto-generated method stub
            
        }

}

 

布局配置文件:随便丢了几个Button在里面:

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/player"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="17dp"
        android:layout_marginTop="40dp"
        android:text="player" />

    <Button
        android:id="@+id/pause"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/player"
        android:layout_below="@+id/player"
        android:layout_marginTop="18dp"
        android:text="pause" />

    <Button
        android:id="@+id/restart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/pause"
        android:layout_centerVertical="true"
        android:text="restart" />

    <Button
        android:id="@+id/stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/restart"
        android:layout_below="@+id/restart"
        android:layout_marginTop="18dp"
        android:text="stop" />

    <Button
        android:id="@+id/seek"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/stop"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="34dp"
        android:text="seek 1 min" />

    <Button
        android:id="@+id/init"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="17dp"
        android:layout_toRightOf="@+id/seek"
        android:text="init before player everytime" />

RelativeLayout>

 

 

音乐播放文件,我给的是jay的一首 "珊瑚海"

在res目录下新建raw文件夹,让后把mp3文件放到这个目录下即可,文件名为 "shanhuhai.mp3"

 

基本上就可以使用了,差不多了.

 

转载于:https://www.cnblogs.com/MMLoveMeMM/articles/4360761.html

你可能感兴趣的:(MediaPlayer 实现播放,暂停,续播等功能)