我的应用程序中有一首歌,我希望能够通过媒体控制器进行控制,我有一些代码,我认为这些代码可以准确地表示如何执行此操作,但是我的代码中出现了2个错误,我会详细说明,有人可以帮助我。
错误1:MediaController类型中的方法setMediaPlayer(MediaController.MediaPlayerControl)不适用于参数(MediaPlayer)
错误2:方法setMediaController(MediaController)未定义类型MediaPlayer
到目前为止我的代码:
MediaPlayer Song;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN );
setContentView(R.layout.billy);
Song = MediaPlayer.create(BillyConnoly.this, R.raw.clip_1);
MediaController mc = new MediaController(this);
mc.setMediaPlayer(Song);
Song.setMediaController(mc);
}
答案 0 :(得分:1)
首先,您需要定义播放器,控制器和处理程序字段:
private MediaPlayer mediaPlayer;
private MediaController mediaController;
private Handler handler = new Handler();
接下来,您需要实例化所有适当的对象(就像您所做的那样),并注册OnPreparedListener:
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaController = new MediaController(this);
然后,准备并启动mediaPlayer:
try {
mediaPlayer.setDataSource(audioFile);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
Log.e(TAG, "Could not open file " + audioFile + " for playback.", e);
}
准备好mediaPlayer后,控制器将被设置:
public void onPrepared(MediaPlayer mediaPlayer) {
Log.d(TAG, "onPrepared");
mediaController.setMediaPlayer(this);
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
}
现在更有意义了吗?
编辑:这是你从res / raw文件夹中播放文件的方式:
int resID=getResources().getIdentifier("filename", "raw", getPackageName());
MediaPlayer mediaPlayer=MediaPlayer.create(this,resID);