android 使用MediaPlayer对网上的录音文件和本地的录音文件进行播放

首先声明权限,第一个用于录音和播放,第二个用于手机文件系统读写,第三个可以用来访问网络上的媒体文件

   <uses-permission android:name="android.permission.RECORD_AUDIO"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  <uses-permission android:name="android.permission.INTERNET"/>

布局控件

<?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="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Document tittle.pdf" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/dp45"
        android:gravity="center"
        android:orientation="horizontal">

        <View
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <ImageButton
            android:id="@+id/play_stop"
            android:layout_width="30dp"
            android:layout_height="60dp"
            android:background="@null"
            android:src="@mipmap/play" />

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

        <TextView
            android:id="@+id/music_cur"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="00:12" />

        <View
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

    </LinearLayout>

    <View style="@style/common_divider_task" />
</LinearLayout>

样子如下

封装java代码,主要注意几点

  1. 首先传入的构造参数为该播放界面,播放地址(可以为本地地址,也可以是网络存放地址),和存放播放小空间的activity
  2. timer用于更新seek的进度和显示
  3. 注意mediaplayer的初始化操作,  mediaPlayer.setDataSource(mp3Path);//指定音频文件的路径

            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.prepareAsync();//让mediaplayer进入准备状态

package com.ltt.overseas.main.tab.fragment.activity;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;


import com.ltt.overseas.R;
import com.ltt.overseas.http.CustomerCallBack;
import com.ltt.overseas.model.ExploreResponseDataBean;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2018/6/24 0024.
 */

public class AudioImageActivity {
    private ImageView mSoundIamge;
    private SeekBar seekBar;
    private TextView musicCur;
    private String mMp3Path = "";//录音存放位置
    private View mView = null;    
    private Activity mParentActivity;
    private SimpleDateFormat format=null;
    private Timer timer;   
    private MediaPlayer mediaPlayer;
    public AudioImageActivity(View view, String mp3Path, Activity activity) {
        format = new SimpleDateFormat("mm:ss");
        mView = view;
        mMp3Path = mp3Path;
        mParentActivity=activity;
        initUI();

    }

    private void initUI() {

        mSoundIamge = mView.findViewById(R.id.play_stop);
        seekBar = mView.findViewById(R.id.seekbar);
        musicCur = mView.findViewById(R.id.music_cur);
        mSoundIamge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                clickPlayVoice(mMp3Path);

            }
        });

    }

    protected void finalize() {

        if (timer != null){
            timer.cancel();
            timer=null;
        }
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer=null;;
        }


    }


    //由Uri转成路径的方法
    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    //点击语音播放按钮
    private void clickPlayVoice(String mp3Path) {
        if (mp3Path.isEmpty())
            return;
         mediaPlayer = new MediaPlayer();
        timer = new Timer();

        try {
            mediaPlayer.setDataSource(mp3Path);//指定音频文件的路径
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.prepareAsync();//让mediaplayer进入准备状态
        } catch (IOException e) {
            e.printStackTrace();
            if (timer != null){
                timer.cancel();
                timer=null;
            }
            if (mediaPlayer != null) {
                mediaPlayer.stop();
                mediaPlayer.release();
                mediaPlayer=null;;
            }

        }

        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                // 在播放完毕被回调
                mSoundIamge.setImageResource(R.mipmap.play);
                if (timer != null){
                    timer.cancel();
                    timer=null;
                }

                if (mediaPlayer != null) {
                    mediaPlayer.stop();
                    mediaPlayer.release();
                    mediaPlayer=null;;
                }



            }
        });
        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
              ;
                if (timer != null){
                    timer.cancel();
                    timer=null;
                }
                if (mediaPlayer != null) {
                    mediaPlayer.stop();
                    mediaPlayer.release();
                    mediaPlayer=null;;
                }
                return true;
            }
        });
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            public void onPrepared(final MediaPlayer mp) {
                seekBar.setMax(mp.getDuration());
                musicCur.setText("00:00");
                mSoundIamge.setImageResource(R.mipmap.stop);
                mp.start();//开始播放
                mp.seekTo(0);

                //监听播放时回调函数
                timer.schedule(new TimerTask() {

                    Runnable updateUI = new Runnable() {
                        @Override
                        public void run() {
                            if (mp == null)
                                return;
                            musicCur.setText(format.format(mp.getCurrentPosition()) + "");

                        }
                    };

                    @Override
                    public void run() {
                        if (mp == null)
                            return;
                        seekBar.setProgress(mp.getCurrentPosition());
                        mParentActivity.runOnUiThread(updateUI);
                    }
                }, 0, 50);

            }
        });
    }



    private String getFileName(String pathandname) {

        int start = pathandname.lastIndexOf("/");
        int end = pathandname.lastIndexOf(".");
        if (start != -1 && end != -1) {
            return pathandname.substring(start + 1, end);
        } else {
            return null;
        }

    }


}

猜你喜欢

转载自blog.csdn.net/mygirlgod/article/details/81068639