第一种:
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.util.Log;
/**
*https://github.com/l123456789jy/Lazy/blob/master/lazylibrary/src/main/java/com/github/lazylibrary/u*til/MediaPlayerUtiles.java
*/
public class MediaPlayerUtiles {
static MediaPlayer mMediaPlayer;
public static MediaPlayer getMediaPlayer() {
if (null == mMediaPlayer) {
mMediaPlayer = new MediaPlayer();
}
return mMediaPlayer;
}
/**
* 播放音频
*/
public static void playAudio(Context mContext, String fileName) {
try {
stopAudio();//如果正在播放就停止
AssetManager assetManager = mContext.getAssets();
AssetFileDescriptor afd = assetManager.openFd(fileName);
MediaPlayer mediaPlayer = getMediaPlayer();
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mediaPlayer.setLooping(false);//循环播放
mediaPlayer.prepare();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
} catch (Exception e) {
Log.e("播放音频失败","");
}
}
/**
* 停止播放音频
*/
public static void stopAudio(){
try {
if (null!=mMediaPlayer){
if (mMediaPlayer.isPlaying()){
mMediaPlayer.pause();
mMediaPlayer.reset();
mMediaPlayer.stop();
}
}
}catch (Exception e){
Log.e("stopAudio",e.getMessage());
}
}
}
第二种
import android.media.AudioManager;
import android.media.MediaPlayer;
import java.io.IOException;
/**
* Created by cooffee on 15/10/20.
*/
public class MediaManager {
private static MediaPlayer mMediaPlayer;
private static boolean isPause;
public static void playSound(String filePath, MediaPlayer.OnCompletionListener onCompletionListener) {
if (null == mMediaPlayer) {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
mMediaPlayer.reset();
return false;
}
});
} else {
mMediaPlayer.reset();
}
try {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setOnCompletionListener(onCompletionListener);
mMediaPlayer.setDataSource(filePath);
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void pause() {
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
isPause = true;
}
}
public static void resume() {
if (mMediaPlayer != null) {
mMediaPlayer.start();
isPause = false;
}
}
public static void release() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
}
网友评论