Android开发05_MediaPlayer之音频播放

一、前言

MediaPlayer类是Android API中专门针对媒体资源的使用开发的一个类,其中包含音频资源和视频资源,使用起来也较简单。


二、音频资源的使用

1、初始化MediaPlayer,有两种方式可以初始化MediaPlayer,直接new或者用静态方法create

// # 1 直接new
mp = new MediaPlayer();
// # 2 使用静态方法创建
mp = MediaPlayer.create(this,R.raw.a);

2、设置音频资源:此方法可传本地资源路径,也可传网络音频网址

mp.setDataSource(musicVo.getPath());

3、准备资源状态:若准备本地资源,可直接使用prepare()方法,若准备网络资源可使用prepareAsync(),另外要准备网络资源要结合准备监听同步使用

// # 1 本地资源的准备
mp.prepare();
// # 2 网络资源的准备
mp.prepareAsync();

4、一旦资源准备完毕,就可以使用MediaPlayer这个强大的类来播放音频资源了

mp.start();

三、MediaPlayer常用属性及方法

1、可使用MediaPlayer对象获取音频资源长度,以及获取音频资源播放的当前长度

mp.getDuration();//总时长
mp.getCurrentPosition();//当前位置

2、可使用MediaPlayer对象将播放资源直接跳到指定位置

//跳到指定位置播放
mp.seekTo(80);

  3、强大的reset,每次播放新的音频资源时,可使用reset将播放器对象重置,清除之前的所有内容

mp.reset();

4、四种监听,都比较容易理解和使用

// #  设置监听(非必需)
mp.setOnCompletionListener(this);//完成监听
mp.setOnErrorListener(this);//错误监听
mp.setOnPreparedListener(this);//准备好的监听
mp.setOnBufferingUpdateListener(this);//缓冲监听

四、获取专辑封面

1、若获取本地已经存在的歌曲专辑封面,可通过ContentProvider获取指定的歌曲的封面图片,以下是获取歌曲封面的工具类

package com.projectb.mediaplayer;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.ParcelFileDescriptor;

import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by macbook on 2016/11/20.
 */

public class MusicGetPic {

    public static Bitmap getArtwork(Context context, long song_id, long album_id, boolean allowdefault) {
        if (album_id < 0) {
            // This is something that is not in the database, so get the album art directly
            // from the file.
            if (song_id >= 0) {
                Bitmap bm = getArtworkFromFile(context, song_id, -1);
                if (bm != null) {
                    return bm;
                }
            }
            if (allowdefault) {
                return getDefaultArtwork(context);
            }
            return null;
        }
        ContentResolver res = context.getContentResolver();
        Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
        if (uri != null) {
            InputStream in = null;
            try {
                in = res.openInputStream(uri);
                return BitmapFactory.decodeStream(in, null, sBitmapOptions);
            } catch (FileNotFoundException ex) {
                // The album art thumbnail does not actually exist. Maybe the user deleted it, or
                // maybe it never existed to begin with.
                Bitmap bm = getArtworkFromFile(context, song_id, album_id);
                if (bm != null) {
                    if (bm.getConfig() == null) {
                        bm = bm.copy(Bitmap.Config.RGB_565, false);
                        if (bm == null && allowdefault) {
                            return getDefaultArtwork(context);
                        }
                    }
                } else if (allowdefault) {
                    bm = getDefaultArtwork(context);
                }
                return bm;
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException ex) {
                }
            }
        }

        return null;
    }

    private static Bitmap getArtworkFromFile(Context context, long songid, long albumid) {
        Bitmap bm = null;
        byte[] art = null;
        String path = null;
        if (albumid < 0 && songid < 0) {
            throw new IllegalArgumentException("Must specify an album or a song id");
        }
        try {
            if (albumid < 0) {
                Uri uri = Uri.parse("content://media/external/audio/media/" + songid + "/albumart");
                ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
                if (pfd != null) {
                    FileDescriptor fd = pfd.getFileDescriptor();
                    bm = BitmapFactory.decodeFileDescriptor(fd);
                }
            } else {
                Uri uri = ContentUris.withAppendedId(sArtworkUri, albumid);
                ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
                if (pfd != null) {
                    FileDescriptor fd = pfd.getFileDescriptor();
                    bm = BitmapFactory.decodeFileDescriptor(fd);
                }
            }
        } catch (FileNotFoundException ex) {

        }
        if (bm != null) {
            mCachedBit = bm;
        }
        return bm;
    }

    private static Bitmap getDefaultArtwork(Context context) {

        Drawable drawable = context.getResources().getDrawable(R.drawable.pic_ax);
        BitmapDrawable bd = (BitmapDrawable) drawable;
        Bitmap bitmap = bd.getBitmap();

        return bitmap;
    }

    private static final Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
    private static final BitmapFactory.Options sBitmapOptions = new BitmapFactory.Options();
    private static Bitmap mCachedBit = null;
}

2、若播放网络端的图片,需要对应的接口才可以获取音频的图片,本地能从ContentProvider中获取,是因为你在下载歌曲的时候就已经把专辑图片一起下载下来了,所以可以获取

3、项目源码:https://github.com/Knight2016/MediaPlayer-


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值