29

I am recording video with MediaRecorder. My code works fine on 2.3.3 but fails on 4.0.3.

The issue is following: the code mediaRecorder.stop() throws the RuntimeExeption

java.lang.RuntimeException: stop failed.
    at android.media.MediaRecorder.stop(Native Method)

with LogCat message

04-05 15:10:51.815: E/MediaRecorder(15709): stop failed: -1007

UPDATE

I've found, that MediaPlayer reports an error (via MediaPlayer.OnErrorListener) almost immediately after the start. Error code is 100 (media server died), extra -1007.

UPDATE 2 Code to prepare the MediaRecorder

            c = Camera.open();

    ...

    // Step 1: Unlock and set camera to MediaRecorder
    camera.unlock();
    mediaRecorder.setCamera(camera);

    // Step 2: Set sources
    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
    mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

    // Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
    CamcorderProfile profile = CamcorderProfile
            .get(CamcorderProfile.QUALITY_HIGH);

    // manual set up!

    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);

    mediaRecorder.setVideoEncodingBitRate(profile.videoBitRate);
    mediaRecorder.setVideoFrameRate(profile.videoFrameRate);
    mediaRecorder.setVideoSize(profile.videoFrameWidth,
            profile.videoFrameHeight);

    mediaRecorder.setAudioChannels(profile.audioChannels);
    mediaRecorder.setAudioEncodingBitRate(profile.audioBitRate);
    mediaRecorder.setAudioSamplingRate(profile.audioSampleRate);

    mediaRecorder.setAudioEncoder(profile.audioCodec);
    //mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
    mediaRecorder.setVideoEncoder(profile.videoCodec);

    // mediaRecorder.setProfile(profile);

    // Step 4: Set output file
    mediaRecorder.setOutputFile("somefile.mp4");

    // Step 5: Set the preview output
    mediaRecorder.setPreviewDisplay(preview.getHolder().getSurface());

    // Step 6: Prepare configured MediaRecorder
    try {
        mediaRecorder.prepare();
    } catch ...
    { release mediaRecorder}

then I simplyCall mediaRecorder.start() please note, that I need video to be encoded into mp4 format. This code works on Samsng Galaxy GIO (android 2.3.3) and fails as described on Acer E305 (android 4.0.2)

Any ideas? Thanks.

Alex
  • 1,319
  • 3
  • 15
  • 33
  • I've found similiar issue but it was not helpful: https://code.google.com/p/android/issues/detail?id=38107 – Alex Apr 05 '13 at 12:21
  • Can you show code for how you prepare the `MediaRecorder` object? – Jason Robinson Apr 09 '13 at 20:33
  • Some code snippet might also be helpful – Royston Pinto Apr 10 '13 at 00:01
  • @JasonRobinson i've udpated the question with the MediaRecorder prepare code – Alex Apr 11 '13 at 06:51
  • @alekz Just to make sure I understand this correctly, it records correctly, it's just stopping it that does not work? Or is it not recording correctly to begin with? – Joachim Isaksson Apr 11 '13 at 07:02
  • @JoachimIsaksson media recorder starts and almost immediately reports an error "[100, -1007] - Media server died". The file is created but it is broken. Exception is thrown when I try to stop MediaRecorder. – Alex Apr 11 '13 at 07:46
  • Try using `CamcorderProfile.QUALITY_LOW` and see if the problem goes away. Even though `QUALITY_HIGH` is suppose to be available and work on every device, I've found that `QUALITY_HIGH` simply doesn't work on some devices. – Jason Robinson Apr 11 '13 at 15:36
  • @JasonRobinson I've tried setting `CamcorderProfile.QUALITY_LOW` but problem remained the same... – Alex Apr 12 '13 at 11:32

6 Answers6

24

Solved it at last. The issue was setting the preview size before setting the actual preview for the camera. The preview size MUST be equal to the selected video size.

CamcorderProfile profile = [get required profile];

Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(profile.videoFrameWidth,profile.videoFrameHeight);
mCamera.setParameters(parameters);

mCamera.setPreviewDisplay([surface holder]);
mCamera.startPreview();

...

//configure MediaRecorder and call MediaRecorder.start()
Alex
  • 1,319
  • 3
  • 15
  • 33
  • 1
    Your a legend :) that helped me a lot. I've had an ongoing issue which this fixed. On certain model phones I was having intermittent problem. in particular the HTC Sensation running 4.x.x wasn't able to record video 100% of the time without first setting the preview size on a surface even though its only 1px wide. I was having strange issues where it would sometimes record bright green striped video or was completely unplayable but only when resolutions of 720x480 or greater. By using `setPreviewSize()` the weird problem was fixed. :) – wired00 May 28 '13 at 06:29
  • thanks it helped me!! but I am getting nullpointer exception when leaving my app. '10-11 22:38:47.609: E/SurfaceView(18569): NullPointerException while updating window. mSession = android.view.IWindowSession$Stub$Proxy@4153f280, mWindow = android.view.SurfaceView$MyWindow@417214b0 10-11 22:38:47.609: E/SurfaceView(18569): Unexpected NullPointerException.' Can you please help me about it. – user2376920 Oct 11 '13 at 17:12
  • I was using this code for a while without any problem, but since I updated my Nexus 6 to Android 6.0, the app is crashing randomly on: `parameters.setPreviewSize' – Jérémy Oct 05 '15 at 19:55
15

Quoting the documentation of "stop" method in MediaRecorder.java in 4.0.3:

Stops recording. Call this after start(). Once recording is stopped, you will have to configure it again as if it has just been constructed. Note that a RuntimeException is intentionally thrown to the application, if no valid audio/video data has been received when stop() is called. This happens if stop() is called immediately after start(). The failure lets the application take action accordingly to clean up the output file (delete the output file, for instance), since the output file is not properly constructed when this happens.

And the fact that MediaPlayer is reporting this "media server died" is due to the same reason. Can you post the rest of your code to see if there's any misconception that may cause this issue?

Jose L Ugia
  • 5,960
  • 3
  • 23
  • 26
  • Thanks for your answer. I've already know about the reason why the Exception is thrown. But I still cannot get, why the configuration of the MediaRecorder is not working on acerE350 (Android 4.0.3) and what does the error "-1007" mean. As to your question - I can post the rest of my code, but it is working robustly on several other phones... I have checked that all methods are called in the right order and it is possible to do the MEdiaRecorders re-config on ServerDied error, but I just whant to configure MediaRenderer to create MP4 video in highest possible quality. – Alex Apr 13 '13 at 18:24
  • 1
    Is there any chance (even if small) that you are starting and stopping the recorder too fast? How many frames (or seconds) are you trying to record? – Jose L Ugia Apr 13 '13 at 19:10
  • I don think so. It works on several budget phones. The code is pretty standard. As to fps - I've tryed 30 (QUALITY_HIGH profile) and 15. Both fail. – Alex Apr 15 '13 at 05:59
  • Theoretically there isn't much more to say (unless one Googler hangs around and gives us some extra insights). If you give me some hints I could try the code on my own devices+emulators. – Jose L Ugia Apr 15 '13 at 07:52
  • thanks) I'll try to find sources for native camera app. At least it works) I'll post the answer if i find out – Alex Apr 15 '13 at 14:15
  • But it seems to be related to the sound not pictures or videos right? – Jose L Ugia Apr 15 '13 at 16:21
  • No, it's all about video( I have not checked sound recording. Will try this bit later when I get my phone back. – Alex Apr 16 '13 at 06:31
  • Have you found an answer yet alekz? :) – Edison Apr 23 '13 at 15:48
  • Starting and stopping the recorder too fast was the issue in my case. Catch the exception on stop(), then discard the resulting file in case you had an exception, otherwise use it. I investigated a lot in this regard, and you should read this http://stackoverflow.com/questions/26986821/detect-when-video-file-has-been-really-written/ Even though I was using cwac it applies to Android as well. Very important to avoid defective video files is to use a FileObserver to detect when the video is finally written by Android. – Oliver Hausler Nov 21 '14 at 05:10
2

I had -1007 error on some devices, mostly with android 9 and finally i solved this problem. The reason was that OMX.google.h264.encoder supports only video sizes evenly dividable by 16. I used displayMetrics.widthPixels and displayMetrics.heightPixels for video size and it is not meet requirements on all devices.

Hope this helps someone!

0

So I found this error being reported for me on the Android emulator for API 18 (after recording was working fine on later versions).

What I found is that if I had called Camera.startPreview() before initialising and starting starting my MediaRecorder instance, I'd get the stop failed: -1007 log when calling MediaRecorder.stop, but if I called Camera.stopPreview() before initialising my MediaRecorder the video would record fine.

I hope this helps

kassim
  • 3,880
  • 3
  • 26
  • 27
  • https://stackoverflow.com/questions/47996933/mediarecorder-keeps-freezing-during-recording-cant-get-it-to-work . That's my code, I'm having this issue, so where am I going wrong? – iBEK Dec 28 '17 at 02:29
0

I experienced the same issue on Samsung J4+, Android 9 Pie.

Fixed it by running mediaRecorder.start() and mediaRecorder.stop() in a Handler:

private val START = 0;
private val STOP  = 1;

inner class CameraHandler(looper: Looper?): Handler(looper) {

  override fun handleMessage(msg: Message?) {
    super.handleMessage(msg)
      try {
        when (msg?.what) {
          START -> mediaRecorder?.start()
          STOP  -> mediaRecorder?.stop()
        }
      } catch (e: Exception) {
        Log.d("debug", e.message)
      }
  }
}

declare the Handler:

private lateinit var mCameraHandler: Handler

initialize in OnCreate with a HandlerThread Looper:

val handlerThread: HandlerThread = HandlerThread("Camera Handler Thread")
handlerThread.start()
mCameraHandler = CameraHandler(handlerThread.looper)

when record or stop button is clicked call:

mCameraHandler.sendEmptyMessage(START)
mCameraHandler.sendEmptyMessage(STOP)

link to my messy code xD

biinui
  • 73
  • 2
  • 6
0

I posted a nice workaround to find if the MediaRecorder is prepared and started. In short, you should check if the MediaRecorder.maxAmplitude > 0, which should be the case if anything was recorded. I am handling this with a helper that keeps checking for the condition until it becomes greater than zero. Read the full explanation here: https://stackoverflow.com/a/66821059/15389960