简体   繁体   English

我应该在哪里调用 MediaPlayer.start();

[英]Where should I call MediaPlayer.start();

I am new to android development:)我是 android 开发的新手:)

I am trying to run audio in the background using MediaPlayer, I have a foreground service set up my question is where should I call the mediaPlayer.start() do I just call it inside the service class, or do I call it in the activity class and start the service at the same time or do I have to run a thread and call the mediaPlayer.start() inside it while calling the thread inside a service class or activity class?我正在尝试使用 MediaPlayer 在后台运行音频,我有一个前台服务设置我的问题是我应该在哪里调用mediaPlayer.start()我只是在服务 class 中调用它,还是在活动中调用它class 并同时启动服务,还是在调用服务 class 或活动 class 中的线程时必须运行一个线程并在其中调用mediaPlayer.start()

I tried calling it inside a service class and inside the activity class while calling startService() everything worked fine and the audio did not stop after a while.我尝试在服务 class 和活动 class 中调用它,同时调用startService()一切正常,一段时间后音频没有停止。

You should start media player inside activity class:您应该在活动 class 中启动媒体播放器:

// media player uses context to create instance
MediaPlayer mediaPlayer = new MediaPlayer(this);
MediaMetadata mediaMetaData = new MediaMetadata.Builder()
                .putString(MediaMetadata.METADATA_KEY_TITLE, "Your video title").build();

UriMediaItem item = new UriMediaItem.Builder(Uri.parse(url))
                .setMetadata(mediaMetaData) // optional
                .build();

sourceVideoPreview.setPlayer(mediaPlayer);
mediaPlayer.setMediaItem(item);
mediaPlayer.prepare();
mediaPlayer.play();

Note: This code works and you can use it outside activity too, but you need to pass context outside activity to create media player instance.注意:此代码有效,您也可以在活动外部使用它,但您需要在活动外部传递上下文以创建媒体播放器实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM