简体   繁体   中英

How to play particular audio on exoplayer when clicked on listview using service?

I have a following code inside onCreate method of service class AudioPlayerService.java

for (Samples.Sample sample : SAMPLES) {
  MediaSource mediaSource = new ExtractorMediaSource.Factory(cacheDataSourceFactory)
      .createMediaSource(sample.uri);
  concatenatingMediaSource.addMediaSource(mediaSource);
}
player.prepare(concatenatingMediaSource);
player.setPlayWhenReady(true);

This service class is tiggered from MainActivity.

Intent intent = new Intent(this, AudioPlayerService.class);
Util.startForegroundService(this, intent);

And MainActivity class has a listview

ListView listView = findViewById(R.id.list_view);
listView.setAdapter(
    new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, SAMPLES));
listView.setOnItemClickListener(new OnItemClickListener() {
  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    ProgressiveDownloadAction action = new ProgressiveDownloadAction(
        SAMPLES[position].uri, false, null, null);
    AudioDownloadService.startWithAction(
        MainActivity.this,
        AudioDownloadService.class,
        action,
        false);
  }
});

Now i want to tell service class to play particular item of the list to play when item on the list is clicked. I thought of using intent to pass data between activity and service. But i could not communicate effectively because onCreate method of service class does not receive data as it cannot process intent.

Please help. Thanks in advance.

I solved it by passing the position of media source, obtained from list item when clicked, through intent from calling activity and receiving inside onStartCommand of service and applying seekTo function as follows:

exoPlayer.seekTo(position, C.TIME_UNSET);

Here position is an integer passed from activity and received on service through the use of intent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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