Exoplayer2流式HLS视频,有时播放仅带有声音的视频(不播放视频)

时间:2019-12-25 07:13:06

标签: android kotlin http-live-streaming exoplayer exoplayer2.x

我在我的应用中实现了exoplayer2来播放HLS视频,但有时它只能播放声音,并且无法正常工作。我应该做些什么?我找不到为什么有时会发生这种情况。

这是初始化播放器的代码

fun initPalyer(){
  val mainHandler = Handler()
  val bandwidthMeter: BandwidthMeter = DefaultBandwidthMeter.Builder(context).build()

  bandwidthMeter.addEventListener(mainHandler!!, this)

 val trackSelectionFactory: TrackSelection.Factory = AdaptiveTrackSelection.Factory()

  trackSelector = DefaultTrackSelector(context, trackSelectionFactory)

  val builder = ParametersBuilder(context)

  trackSelectorParameters = builder.build()
  trackSelector!!.parameters = trackSelectorParameters


    var rendersFactory: RenderersFactory = app.buildRenderersFactory(false)

    player = SimpleExoPlayer.Builder(
          context, renderersFactory
   )
   .setTrackSelector(trackSelector!!)
   .setBandwidthMeter(bandwidthMeter)
    //.setLoadControl(loadControl)
   .build()

    player!!.addListener(this)

    loadState()
    playerView.player = player!!

}

准备播放器的代码

private fun preparePlayer(uri: Uri) {
        val mediaSource = MediaSourceBuilder().build(uri)

        durationSet = false
        player?.prepare(mediaSource, true, false)
    }

以及用于创建mediaSources的代码

class MediaSourceBuilder {

    //Build various MediaSource depending upon the type of Media for a given video/audio uri
    fun build(uri: Uri): MediaSource {
        val userAgent = PlayerConstants.USER_AGENT
        val lastPath = uri.lastPathSegment?:""

        val defaultHttpDataSourceFactory = DefaultHttpDataSourceFactory(userAgent)

        if(lastPath.contains(PlayerConstants.FORMAT_MP3) || lastPath.contains(PlayerConstants.FORMAT_MP4)){

            return ExtractorMediaSource.Factory(defaultHttpDataSourceFactory)
                .createMediaSource(uri)

        }else if(lastPath.contains(PlayerConstants.FORMAT_M3U8)){

            return HlsMediaSource.Factory(defaultHttpDataSourceFactory)
                .setAllowChunklessPreparation(true)
                .createMediaSource(uri)

        }else{
            val dashChunkSourceFactory = DefaultDashChunkSource.Factory(defaultHttpDataSourceFactory)

            return DashMediaSource.Factory(dashChunkSourceFactory, defaultHttpDataSourceFactory)
                .createMediaSource(uri)

        }
    }

1 个答案:

答案 0 :(得分:1)

您可能想更改DataSourceFactory,以防URL使用HTTPS,可能会导致错误,请尝试使用DefaultDataSourceFactory而不是DefaultHttpDataSourceFactory