【问题标题】:Media player getting IllegalStateException at setDataSource媒体播放器在 setDataSource 处获得 IllegalStateException
【发布时间】:2015-02-26 19:40:46
【问题描述】:

我调试了一下,看到path = /storage/emulated/0/Music/test_cbr.mp3

经过测试

mp.setDataSource(path); 

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

但是两种方式都会在 setDataSource 处给出非法状态异常,为什么?

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 拼错为 mediaplayer。现在我纠正它。感谢朋友们的帮助。

【问题讨论】:

  • 你能发布你的错误堆栈跟踪吗?

标签: android android-mediaplayer illegalstateexception


【解决方案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();

【讨论】:

    【解决方案2】:

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

    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();
        }
    });
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多