Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know when MediaRecorder has finished writing data to file

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?

like image 725
Stefan H Singer Avatar asked Sep 14 '11 14:09

Stefan H Singer


People also ask

Does Safari support MediaRecorder?

MediaRecorder API is Not Supported on Safari 13, which means that any user who'd be accessing your page through Safari 13 can see it perfectly.

What is media recorder on Iphone?

Media Recorder records both audio and video recordings and save them into many different formats of your liking with just a few simple taps! All recordings will automatically appear on the Files app.


2 Answers

The FileObserver class suits your needs perfectly. Here is the documentation. It's easy to use. When a observed file is closed after writing, the onEvent callback is called with CLOSE_WRITE as the parameter.

MyFileObserver fb = new MyFileObserver(mediaFile_path, FileObserver.CLOSE_WRITE);
fb.startWatching();

class MyFileObserver extends FileObserver {

    public MyFileObserver (String path, int mask) {
        super(path, mask);
    }

    public void onEvent(int event, String path) {
        // start playing
    }
}

Don't forget to call stopWatching().

like image 146
Ronnie Avatar answered Oct 18 '22 22:10

Ronnie


We solved similar problem with the following algo:

while (file not complete)
    sleep for 1 sec
    read the fourth byte of the file
    if it is not 0 (contains 'f' of the 'ftyp' header) then
        file is complete, break

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.

like image 44
Ash Avatar answered Oct 18 '22 22:10

Ash