媒体播放器在setDataSource上获取IllegalStateException

时间:2015-02-26 08:21:11

标签: android android-mediaplayer illegalstateexception

我调试并看到path = /storage/emulated/0/Music/test_cbr.mp3

并测试

mp.setDataSource(path); 

mp.setDataSource(getApplicationContext(),Uri.parse(path));

但两种方式都会在setDataSource中给出illegalStateException么?

try 
        {

            MediaPlayer mp = new MediaPlayer();

              //  Uri fileUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, 1834);

              //  mp.setDataSource(context, fileUri);


            mp.setAudioStreamType(AudioManager.STREAM_MUSIC);

            mp.release();

            mp.reset();

            mp.setDataSource(getApplicationContext(),Uri.parse(path));

              //  mp.reset();

            //    mp.setDataSource(context, uri);    


            mp.prepare();


            mp.start();

            } catch (IllegalArgumentException e) {
                 e.printStackTrace();
              } catch (SecurityException e) {
                 e.printStackTrace();
              } catch (IllegalStateException e) {
                 e.printStackTrace();
              } catch (IOException e) {
                 e.printStackTrace();
              }

编辑和回答

现在一切正常。我向媒体播放器拼错了mp。现在我纠正它。感谢您的帮助朋友。

2 个答案:

答案 0 :(得分:1)

只需尝试我的代码

    MediaPlayer mp = new MediaPlayer();
    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
    try {

        mp.setDataSource(getApplicationContext(), Uri.parse("path"));
        mp.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }
    mp.start();

答案 1 :(得分:1)

在您的活动类中创建媒体播放器的全局对象:

MediaPlayer mediaPlayer;//global object
String path = "/storage/emulated/0/Music/test_cbr.mp3";

在活动类的oncreate方法中编写以下代码:

mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(path);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new OnPreparedListener()
{

    @Override
    public void onPrepared(MediaPlayer mp)
    {
        // TODO Auto-generated method stub
        mediaPlayer.start();
    }
});

我希望这个解决方案可以帮到你。