Exoplayer播放m3u8文件Android

lyfkaqu1  于 2023-01-07  发布在  Android
关注(0)|答案(7)|浏览(912)

在尝试了使用Videoview和MediaPlayer播放M3U8文件的多种方式后,我决定给予。每次我播放M3U8文件时,我只听到声音。(请不要写来自堆栈溢出的URL来回答我的问题。我已经把它们都红了)一直在四处打听,我终于知道exoplayer可能是我正在寻找的。但是exoplayer似乎是一个新手,我找不到任何适当的教程。我自己是个新手,所有关于tracker和blabla的讨论对我来说都太复杂了,我只想在我的应用程序中从不同的url打开我所有的m3u8文件,而不用把它们传递给vlc或任何外部意图。
为了记录在案,我使用奇巧和以上。所以exoplayer应该是可实现的。
所以我迫切需要的是一个简单的教程,告诉我如何使用exoplayer或者其他任何显示视频和播放音频的方式来播放我的m3u8文件,而不是只是其中之一。请不要把我链接到谷歌开发上的exoplayer页面。我也去过那里。
提前感谢:)

hl0ma9xz

hl0ma9xz1#

在Android 4.1+上,您可以使用https://github.com/brianwernick/ExoMedia/库。Read-me页面上提到的示例应该足以让您入门。我复制了该代码片段,并做了一些补充/修改。

private void setupVideoView() {
                EMVideoView emVideoView = (EMVideoView)findViewById(R.id.video_play_activity_video_view);
                emVideoView.setOnPreparedListener(this);

                //Enter your m3u8 URL below
                emVideoView.setVideoURI(Uri.parse("http://SOMESERVER/playlist.m3u8"));
            }

            @Override
            public void onPrepared(MediaPlayer mp) {
                //Starts the video playback as soon as it is ready
                emVideoView.start();
            }

            @Override
            public void onPause() {
                super.onPause();
                //Pause Video Playback
                emVideoView.pause();
            }
fcy6dtqo

fcy6dtqo2#

我已经创建了一个演示应用程序来播放M3U8媒体文件
首先将gradle依赖项添加到文件中

compile 'com.google.android.exoplayer:exoplayer:r2.4.0'

创建一个简单的布局文件,将storage master.m3u8路径作为输入,并使用SimpleExoPlayerView视图播放下载的文件。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout mlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent" android:layout_height="match_parent">

<android.support.design.widget.TextInputEditText
  android:layout_marginTop="15dp"
android:layout_width="match_parent"
   android:id="@+id/mediaPath"
   android:layout_height="56dp" />
   <android.support.v7.widget.AppCompatButton
android:id="@+id/play"
       android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
       android:layout_below="@+id/mediaPath"
       android:background="@color/colorAccent"
android:layout_width="match_parent"
android:text="Play"
android:layout_height="56dp" />
<com.google.android.exoplayer2.ui.SimpleExoPlayerView
   android:layout_below="@+id/play"
   android:id="@+id/video_view"
   android:layout_marginTop="5dp"
   android:layout_width="match_parent"
   android:layout_height="match_parent"/>
</RelativeLayout>

创建一个简单的ExoPlayer Activity来播放文件。

public class ExoPlayer  extends AppCompatActivity{
Context mContext;
SimpleExoPlayerView playerView;
EditText editText;
private ComponentListener componentListener;
private DataSource.Factory mediaDataSourceFactory;
private Handler mainHandler;
private DefaultTrackSelector trackSelector;
SimpleExoPlayer player;
private static final DefaultBandwidthMeter BANDWIDTH_METER = new        DefaultBandwidthMeter();



@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_exoplayer);
   mContext =this;
   editText = (EditText) findViewById(R.id.mediaPath);
   Button btnPlay = (Button) findViewById(R.id.play);
   playerView  = (SimpleExoPlayerView)findViewById(R.id.video_view);
   mediaDataSourceFactory = buildDataSourceFactory(true);
   mainHandler = new Handler();
   componentListener = new ComponentListener();
   trackSelector = new DefaultTrackSelector();
   btnPlay.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View view) {
      if(editText.getText()!=null && editText.getText().length()>0){
               initializePlayer(editText.getText().toString());
           }
       }
   });
}
   private DataSource.Factory buildDataSourceFactory(boolean useBandwidthMeter) {
   return ((AnalyticsApplication) getApplication())
           .buildDataSourceFactory(useBandwidthMeter ? BANDWIDTH_METER : null);
 }

   private void initializePlayer(String path) {
   player = ExoPlayerFactory.newSimpleInstance(mContext, trackSelector);
   player.addListener(componentListener);
//        String path = file:///storage/emulated/0/SugarBox/master.m3u8";
   Uri uri = Uri.parse(path);
   MediaSource mediaSource = buildMediaSource(uri);
   player.prepare(mediaSource, true, false);
   playerView.setPlayer(player);
 }
  private MediaSource buildMediaSource(Uri uri) {
 return new HlsMediaSource(uri, mediaDataSourceFactory, mainHandler, null);
 }
 private void releasePlayer() {
   if (player != null) {
       player.removeListener(componentListener);
       player.release();
       player = null;
   }
   }


 @Override
 public void onStart() {
   super.onStart();
   if (Util.SDK_INT > 23) {
       if(editText.getText()!=null && editText.getText().length()>0){
           initializePlayer(editText.getText().toString());
       }
   }
 }



@Override
   public void onResume() {
   super.onResume();
   if ((Util.SDK_INT <= 23 || player == null)) {
       if(editText.getText()!=null && editText.getText().length()>0){
           initializePlayer(editText.getText().toString());
       }
   }
 }


@Override
 public void onPause() {
   super.onPause();
   if (Util.SDK_INT <= 23) {
       releasePlayer();
   }
}


 @Override
public void onStop() {
   super.onStop();
   if (Util.SDK_INT > 23) {
       releasePlayer();
   }
}





   private class ComponentListener implements com.google.android.exoplayer2.ExoPlayer.EventListener{

   @Override
   public void onPlayerStateChanged(boolean playWhenReady,
                                    int playbackState) {
       String stateString;
       switch (playbackState) {
           case com.google.android.exoplayer2.ExoPlayer.STATE_IDLE:
               stateString = "ExoPlayer.STATE_IDLE      -";
               break;
           case com.google.android.exoplayer2.ExoPlayer.STATE_BUFFERING:
               stateString = "ExoPlayer.STATE_BUFFERING -";
               break;
           case com.google.android.exoplayer2.ExoPlayer.STATE_READY:
               stateString = "ExoPlayer.STATE_READY     -";
               break;
           case com.google.android.exoplayer2.ExoPlayer.STATE_ENDED:
               stateString = "ExoPlayer.STATE_ENDED     -";
               break;
           default:
               stateString = "UNKNOWN_STATE             -";
               break;
       }
       Log.d("ExopLayer", "changed state to " + stateString
               + " playWhenReady: " + playWhenReady);
   }

   @Override
   public void onTimelineChanged(Timeline timeline, Object manifest) {}
   @Override
   public void onTracksChanged(TrackGroupArray trackGroups,
                               TrackSelectionArray trackSelections) {}
   @Override
   public void onLoadingChanged(boolean isLoading) {}
   @Override
   public void onPlayerError(ExoPlaybackException error) {}
   @Override
   public void onPositionDiscontinuity() {}
   @Override
   public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {}
  }


private DrmSessionManager<FrameworkMediaCrypto> buildDrmSessionManager(UUID uuid,   String licenseUrl, String[] keyRequestPropertiesArray) throws UnsupportedDrmException {
   if (Util.SDK_INT < 18) {
       return null;
   }
   HttpMediaDrmCallback drmCallback = new HttpMediaDrmCallback(licenseUrl,
           buildHttpDataSourceFactory(false));
   if (keyRequestPropertiesArray != null) {
       for (int i = 0; i < keyRequestPropertiesArray.length - 1; i += 2) {
           drmCallback.setKeyRequestProperty(keyRequestPropertiesArray[i],
                   keyRequestPropertiesArray[i + 1]);
       }
   }
   return new DefaultDrmSessionManager<>(uuid,
           FrameworkMediaDrm.newInstance(uuid), drmCallback, null, mainHandler, null);
 }



  private HttpDataSource.Factory buildHttpDataSourceFactory(boolean useBandwidthMeter) {
   return ((AnalyticsApplication) getApplication())
           .buildHttpDataSourceFactory(useBandwidthMeter ? BANDWIDTH_METER : null);

  }

}
eqoofvh9

eqoofvh93#

这是使用ExoPlayer库流式传输m3u8文件的最简单方法,希望对https://github.com/karim23/SimpleStreamPlayer/tree/master有所帮助

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = getApplicationContext();
    setContentView(R.layout.activity_main);
    //change the live streaming URL with yours. 
    contentUri = "http://abclive.abcnews.com/i/abc_live4@136330/index_1200_av-b.m3u8?sd=10&b=1200&rebase=on";
    // contentType = DemoUtil.TYPE_HLS;
    final Intent intent = new Intent(context, VideoPlayerActivity.class).setData(Uri.parse(contentUri))
            .putExtra(VideoPlayerActivity.CONTENT_ID_EXTRA, -1)
            //Change the type according to the live streaming extension.
            .putExtra(VideoPlayerActivity.CONTENT_TYPE_EXTRA, DemoUtil.TYPE_HLS);
    liveStreamingTv =(TextView)findViewById(R.id.mainActivity_liveStreamingTv);
    liveStreamingTv.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            startActivity(intent);
        }
    });
}
pbgvytdp

pbgvytdp4#

我已经用以下代码处理过m3u8

videoView = findViewById(R.id.videoViewXml);

    final ProgressDialog progressDialog = new ProgressDialog(VideoActivity.this);
    progressDialog.setMessage("Please Wait");
    progressDialog.setCancelable(false);
    progressDialog.show();

    MediaController mediaController = new MediaController(this);
    mediaController.setAnchorView(videoView);
    videoView.setMediaController(mediaController);

    videoView.setVideoURI(Uri.parse(VIDEO_PATH));
    videoView.start();

    videoView.setOnPreparedListener(new OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            progressDialog.dismiss();
        }
    });
gjmwrych

gjmwrych5#

目前还没有关于ExoPlayer的教程。ExoPlayerMediaPlayer的最佳替代品,但目前对新手不太友好。
您需要做的是转到github页面,查看demo应用程序中的DemoPlayer类。
这个应用程序可以打开很多不同的格式,包括hls

ewm0tg9j

ewm0tg9j6#

解决播放m3u8文件时黑屏的问题,我已经用这个解决了,
实现'com.谷歌.安卓.外放:外放:2.13.3'
媒体源代码:

private fun buildMediaSource(uri: Uri): MediaSource {
    
            val userAgent = "exoplayer-codelab"
    
            return if (uri.lastPathSegment!!.contains("mp3") || uri.lastPathSegment!!.contains("mp4")) {
                ExtractorMediaSource.Factory(DefaultHttpDataSourceFactory(userAgent))
                    .createMediaSource(uri)
            } else {
                HlsMediaSource.Factory(DefaultHttpDataSourceFactory(userAgent))
                    .createMediaSource(uri)
            }
}

媒体来源:

val mediaSource = buildMediaSource(Uri.parse(stories[counter].mediaUrl))
 simpleExoPlayer.prepare(mediaSource, false, false)
qncylg1j

qncylg1j7#

DataSource.Factory fdataSourceFactory = new FileDataSource.Factory();
DataSource.Factory ddataSourceFactory = new DefaultHttpDataSource.Factory();
if (urlAll.startsWith("http") ) {
  // Create a HLS media source pointing to a playlist uri.
  MediaSource hlsMediaSource = new HlsMediaSource.Factory(ddataSourceFactory)
                                    .setAllowChunklessPreparation(false)
                                    .createMediaSource(mediaItem);
  player.addMediaSource(index, hlsMediaSource);
}
else {
  // Create a HLS media source pointing to a playlist uri.
  MediaSource hlsMediaSource = new HlsMediaSource.Factory(fdataSourceFactory)
                                    .setAllowChunklessPreparation(false)
                                    .createMediaSource(mediaItem);
  player.addMediaSource(index, hlsMediaSource);
}

相关问题