无法将MediaPlayerController投射到音乐播放器 - 获得异常

时间:2014-10-25 09:13:09

标签: android audio-player mediacontroller android-music-player

你好我试图在我的音乐播放器应用程序中使用媒体播放器控制器,但是当我使用musicplayer.setMediaPlayer时,我得到了一个例外。这是我的代码片段和logcat错误。

musicPlayer = MediaPlayer.create(MusicPlayer.this, uri);
        musicPlayer.setWakeMode(this.getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
        MediaController musicControl = new MediaController(this);
        musicControl.show();
        musicControl.setMediaPlayer((MediaPlayerControl) musicPlayer);
        musicPlayer.start();

这是logcat

Process: com.tproductions.Openit, PID: 11382
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tproductions.Openit/com.tproductions.Openit.MusicPlayer}: java.lang.ClassCastException: android.media.MediaPlayer cannot be cast to android.widget.MediaController$MediaPlayerControl
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2237)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
        at android.app.ActivityThread.access$800(ActivityThread.java:144)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:212)
        at android.app.ActivityThread.main(ActivityThread.java:5135)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:877)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.ClassCastException: android.media.MediaPlayer cannot be cast to android.widget.MediaController$MediaPlayerControl
        at com.tproductions.Openit.MusicPlayer.onCreate(MusicPlayer.java:49)
        at android.app.Activity.performCreate(Activity.java:5231)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)

任何想法如何解决这个问题?非常感谢

1 个答案:

答案 0 :(得分:0)

问题是MediaPlayer没有实现MediaController.MediaPlayerControl

你有两个我能想到的选择......

首选是扩展MediaPlayer并实现接口。实施例...

public class MyMediaPlayer extends MediaPlayer
    implements MediaController.MediaPlayerControl {

    ...

}

...这样您就可以在MyMediaPlayer的调用中使用musicControl.setMediaPlayer(...)的实例。

或者,只需在Activity上实施界面即可。实施例...

public class MyActivity extends Activity
    implements MediaController.MediaPlayerControl {

    ...

}

当您在musicControl.setMediaPlayer(...)中致电Activity时,您只需将this作为参数传递。