首页 > 解决方案 > 录制 RTMP 流

问题描述

我有一堂课,在 ExoPLayer 的帮助下观看 rtmp 流:

    player = ExoPlayerFactory.newSimpleInstance(context)
    val rtmpDataSourceFactory = RtmpDataSourceFactory()
    val videoSource = ProgressiveMediaSource.Factory(rtmpDataSourceFactory)
            .createMediaSource(Uri.parse(streamURL))

    player.prepare(videoSource)
    player.setVideoTextureView(playerView)
    player.playWhenReady = true

playerView是 TextureView,而不是 SurfaceView,因为我还需要从流中截取屏幕截图。

据我所知,ExoPlayer 没有流录制的方法,只有下载,所以问题是 - 我怎样才能录制 rtmp 流?我搜索了很多库和堆栈问题,但仍然找不到干净、正常的解决方案。

目前我正在尝试通过基本的 MediaRecorder 记录流,并在 Android 开发人员文档的帮助下,但我仍然不明白,MediaRecorder 如何获取流数据或至少表面。

val path = "${Environment.getExternalStorageDirectory()}${File.separator}${Environment.DIRECTORY_DCIM}${File.separator}${"FILE_NAME"}"

        recorder = MediaRecorder().apply {
            setVideoSource(MediaRecorder.VideoSource.SURFACE)
            setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
            setOutputFile(path)

            start()
        }

标签: androidrtmpexoplayer

解决方案


我通过使用 FFMpeg 库找到了解决方案。如果有人需要它 - 添加这个 Gradle 依赖项: implementation 'com.writingminds:FFmpegAndroid:0.3.2

这是代码:

        // Build path for recorded video
        val title = "/" + System.currentTimeMillis().toString() + ".mp4"
        val targetFile = File(getExternalStoragePublicDirectory(DIRECTORY_DCIM).toString() + title)

        // FFMpeg command for stream recording
        val command = arrayOf("-i", streamURL, "-acodec", "copy", "-vcodec", "copy", targetFile.toString())

        try {
            // Load the binary
            ffmpeg.loadBinary(object : LoadBinaryResponseHandler() {})
        } catch (e: FFmpegNotSupportedException) {
            e.printStackTrace()
        }

        try {
            // Execute command
            ffmpeg.execute(command, object : ExecuteBinaryResponseHandler() {})
        } catch (e: FFmpegCommandAlreadyRunningException) {
            e.printStackTrace()
        }

推荐阅读