如何知道 MediaRecorder 何时完成将数据写入文件
在进行实际录制之前,我们使用 MediaRecorder 使用 setOutputFile() 将视频录制到外部存储上的文件中。
一切正常,但主要问题是,录制完成后,我们希望开始在 VideoView 中播放录制的视频。
如何知道文件何时可以读取和播放?
We're using MediaRecorder to record video to a file on the external storage using setOutputFile() before doing the actual recording.
Everything works fine, but the main issue is that as soon as the recording is done, we want to start playing the recorded video back in a VideoView.
How to know when the file is ready to be read and played back?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
FileObserver
类完全满足您的需求。 这里是文档。它很容易使用。当观察到的文件在写入后关闭时,会以CLOSE_WRITE
作为参数调用onEvent
回调。不要忘记调用
stopWatching()
。The
FileObserver
class suits your needs perfectly. Here is the documentation. It's easy to use. When a observed file is closed after writing, theonEvent
callback is called withCLOSE_WRITE
as the parameter.Don't forget to call
stopWatching()
.我们用以下算法解决了类似的问题:
关键是 MediaRecorder 在最后一刻写入了 ftyp 框。如果它就位,则文件完整。
We solved similar problem with the following algo:
The key point is that MediaRecorder writes the ftyp box at the very last moment. If it is in place, then the file is complete.
在我的测试中,无论录制的大小如何, mediaRecorder.stop() 都是一种阻塞方法,仅在文件完全写入并被媒体录制器关闭后才返回。
所以JPM的回答其实是正确的。
您可以通过在 stop() 之后立即调用 File.length() 来验证这一点。你会发现此时输出的文件长度就是文件的最终长度。换句话说,在 stop() 返回后,媒体记录器不会再向文件写入任何内容。
In my tests irrespective of the size of the recording mediaRecorder.stop() is a blocking method that only returns after the file has been completely written and closed by the media recorder.
So JPMs answer is actually correct.
You can verify this by calling File.length() immediately after stop(). You will find that the output file length is the final length of the file at this point. In other words media recorder does not write anything further to the file after stop() has returned.
我自己没有尝试过,但这可能有效:
如果它按照它所说的那样操作,那么我想如果您调用此方法并且在该方法返回后您就知道文件已准备好。
I haven't tried this myself but this might work:
If it does what it says, then I guess if you call this and after this method returns you know the file is ready.
显然,无法检测媒体播放器中的录制何时停止,但如果您创建实现 MediaRecorder 的自定义类,则可以覆盖 stop() 。在这里我会做这样的事情:
然后您可以访问布尔值以查看它是否已停止录制。
Apparently there is no way to detect when the recording has stopped in Media player, but there is a stop() that you can override if you create a custom class that implements MediaRecorder. here I would do something like this:
Then you can access the boolean to see if it has stopped recording.
一种肮脏的方法是检查文件的
lastModified()
值,如果文件在 2 秒内没有修改,则打开 VideoView。A dirty way would be to check the
lastModified()
value of the File and open the VideoView if the File wasn't modified for 2 seconds.