在Android的MediaPlayer服务中播放本地mp3

时间:2012-06-12 03:11:44

标签: android media-player

使用服务中的MediaPlayer在SD卡上的默认下载文件夹中播放本地.mp3商店的最佳方法是什么?

该文件现在播放,但是当我尝试调用.pause()函数时,没有任何事情发生。

public class PlayService extends Service{

@Override
public int onStartCommand(Intent intent, int flags, int startId){

    int key = intent.getIntExtra("key", 0);
    MediaPlayer mMediaPlayer = new MediaPlayer();

    FileInputStream fileStream = null;
    try {
        fileStream = new FileInputStream("/sdcard/Download/Bob_Marley-Jammin.mp3");
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    }

    try {
        mMediaPlayer.setDataSource(fileStream.getFD());
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        mMediaPlayer.prepare();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    switch (key) {
    case 0: //Play
        if (mMediaPlayer.isPlaying()){
            break;
        }
        else
            mMediaPlayer.start();
        break;
    case 1: //Pause
        if(mMediaPlayer.isPlaying())
            mMediaPlayer.pause();
        break;
    case 2: //Stop
        if(mMediaPlayer.isPlaying()){
            mMediaPlayer.pause();
            mMediaPlayer.seekTo(0);
        }
        break;
    default:
        break;

1 个答案:

答案 0 :(得分:1)

FileInputStream fileStream = new FileInputStream("/sdcard/Download/Bob_Marley-Jammin.mp3");
mMediaPlayer.setDataSource(fileStream.getFD());