【问题标题】:Accessing the output video while recording录制时访问输出视频
【发布时间】:2013-05-30 03:26:53
【问题描述】:

简而言之,我正在寻找一种在录制视频时从相机获取字节流的方法。 目的是在保存当前录制的某些部分的同时连续录制,而无需停止实际录制过程以访问输出文件。这甚至可能吗,还是我需要实际停止录制并保存它以供播放?

我已经看到项目和开源库允许通过本地套接字和 ParcelFileDescriptor 类从相机实时流式传输到服务器,因此我假设(可能不正确)记录器字节流必须以某种方式访问​​。

任何建议或帮助将不胜感激。

【问题讨论】:

    标签: android recording mediarecorder


    【解决方案1】:

    将输出文件设置为 FileDescriptor:

    mRecorder.setOutputFile(getStreamFd());
    

    然后使用这个函数:

       private FileDescriptor getStreamFd() {
        ParcelFileDescriptor[] pipe = null;
    
        try {
            pipe = ParcelFileDescriptor.createPipe();
    
            new TransferThread(new ParcelFileDescriptor.AutoCloseInputStream(pipe[0]),
                    new FileOutputStream(getOutputFile())).start();
        } catch (IOException e) {
            Log.e(getClass().getSimpleName(), "Exception opening pipe", e);
        }
    
        return (pipe[1].getFileDescriptor());
    }
    
    private File getOutputFile() {
        return (new File(Environment.getExternalStorageDirectory().getPath().toString() + "/YourDirectory/filename"));
    }
    

    新线程代码:

        static class TransferThread extends Thread {
        InputStream in;
        FileOutputStream out;
    
        TransferThread(InputStream in, FileOutputStream out) {
            this.in = in;
            this.out = out;
        }
    
        @Override
        public void run() {
            byte[] buf = new byte[8192];
            int len;
    
            try {
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                in.close();
    
                out.flush();
                out.getFD().sync();
                out.close();
    
            } catch (IOException e) {
                Log.e(getClass().getSimpleName(),
                        "Exception transferring file", e);
            }
        }
    }
    

    不要忘记在清单文件中添加权限:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

    【讨论】:

    • 通过使用这种方法,我得到一个无法播放的视频文件。有什么建议吗?
    【解决方案2】:

    我遇到了类似的问题,想在访问 H264 NAL 单元相机字节流时将 H264 记录在 MP4 文件中(将其重定向到 libRTMP)。以下示例帮助很大(至少需要 Android 4.3):

    http://bigflake.com/mediacodec/

    基本上,Android 的 MediaCodec 类提供对设备编码器/解码器的低级访问。看一下上面例子的函数drainEncoder():

    • 视频数据被发送到 MediaMuxer 以创建输出文件
    • 您可以轻松地从 encodedData ByteBuffer 访问 H264 NAL 单元并按照您想要的方式处理它们

    例子:

    int old_pos = encodedData.position();
    encodedData.position(0);
    byte[] encoded_array = new byte[encodedData.remaining()];
    encodedData.get(encoded_array);
    encodedData.position(old_pos);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      • 1970-01-01
      • 2016-02-14
      • 2012-03-10
      • 1970-01-01
      • 2016-02-13
      相关资源
      最近更新 更多