到MediaPlayer.setDataSource“ java.lang.IllegalStateException”的storageRef.getDownloadUrl

时间:2018-09-07 14:17:48

标签: java android android-mediaplayer

我有这种方法

 public void run() {
    try {
        mp = new MediaPlayer();
        mp.setOnCompletionListener(VMPlayer.this); // Important
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
        final FirebaseStorage storage = FirebaseStorage.getInstance();
        // Create a storage reference from our app
        StorageReference storageRef = storage.getReferenceFromUrl(SongPath);
        storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
            @Override
            public void onSuccess(Uri uri) {
                try {
                    // Download url of file
                    String url = uri.toString();
                    mp.setDataSource(url);
                    // wait for media player to get prepare
                    mp.setOnPreparedListener(VMPlayer.this);
                    mp.prepareAsync();


                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.i("TAG", e.getMessage());
            }
        });


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

哪个需要FirebaseStorage来获取下载URL并开始从Firebase存储中播放歌曲

虽然此方法效果很好,但是如果用户单击另一首歌曲,并且在mp设置数据源之前再次调用此方法,则会收到此错误

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.nightblue.musicdrop, PID: 19284
              java.lang.IllegalStateException
                  at android.media.MediaPlayer.nativeSetDataSource(Native Method)
                  at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1101)
                  at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1062)
                  at com.example.nightblue.musicdrop.ViewModel.VMPlayer$2.onSuccess(VMPlayer.java:117)
                  at com.example.nightblue.musicdrop.ViewModel.VMPlayer$2.onSuccess(VMPlayer.java:111)
                  at com.google.android.gms.tasks.zzn.run(Unknown Source)
                  at android.os.Handler.handleCallback(Handler.java:836)
                  at android.os.Handler.dispatchMessage(Handler.java:103)
                  at android.os.Looper.loop(Looper.java:203)
                  at android.app.ActivityThread.main(ActivityThread.java:6251)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1073)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)

如果mp尚未设置其来源,我当然可以使第二首歌曲不执行任何操作,但这会严重损害演奏效果

0 个答案:

没有答案