RTMP流的录制

Recording of RTMP stream

我有一个 class,在 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 流?我搜索了很多库和 Stack 问题,但仍然找不到干净、正常的解决方案。

目前我正在尝试通过基本的 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()
        }

我通过使用 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()
        }