Android开发之媒体播放工具类完整示例

本文实例讲述了Android开发之媒体播放工具类。分享给大家供大家参考,具体如下:

package com.maobang.imsdk.util;
import android.media.MediaPlayer;
import android.net.Uri;
import android.util.Log;
import java.io.FileInputStream;
import java.io.IOException;
import com.maobang.imsdk.app.IMApplication;
/**
 * 媒体播放工具
 */
public class MediaUtil {
  private static final String TAG = "MediaUtil";
  private MediaPlayer player;
  private EventListener eventListener;
  private MediaUtil(){
    player = new MediaPlayer();
  }
  private static MediaUtil instance = new MediaUtil();
  public static MediaUtil getInstance(){
    return instance;
  }
  public MediaPlayer getPlayer() {
    return player;
  }
  public void setEventListener(final EventListener eventListener) {
    if (player != null){
      player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
          eventListener.onStop();
        }
      });
    }
    this.eventListener = eventListener;
  }
  public void play(FileInputStream inputStream){
    try{
      if (eventListener != null){
        eventListener.onStop();
      }
      player.reset();
      player.setDataSource(inputStream.getFD());
      player.prepare();
      player.start();
    }catch (IOException e){
      Log.e(TAG, "play error:" + e);
    }
  }
  public void stop(){
    if (player != null && player.isPlaying()){
      player.stop();
    }
  }
  public long getDuration(String path){
    player = MediaPlayer.create(IMApplication.getContext(), Uri.parse(path));
    return player.getDuration();
  }
  /**
   * 播放器事件监听
   */
  public interface EventListener{
    void onStop();
  }
}

更多关于Android相关内容感兴趣的读者可查看本站专题:《Android开发入门与进阶教程》、《Android多媒体操作技巧汇总(音频,视频,录音等)》、《Android视图View技巧总结》、《Android编程之activity操作技巧总结》、《Android资源操作技巧汇总》及《Android控件用法总结》

希望本文所述对大家Android程序设计有所帮助。

你可能感兴趣的:(Android开发之媒体播放工具类完整示例)