2012-05-08 16 views
6

Estoy tratando de crear un grabador de video en Android, y he preparado mi código que se supone que funciona, pero constantemente recibo un mensaje de error start failed: -19.Android MediaRecorder - "inicio fallido: -19"

Aquí está mi código:

public boolean startRecording() { 
    try { 
     camera.unlock(); 
     mediaRecorder = new MediaRecorder(); 
     mediaRecorder.setOnErrorListener(new MediaRecorder.OnErrorListener() { 

       @Override 
       public void onError(MediaRecorder mr, int what, int extra) { 
       Log.i(TAG, "Error"); 
      } 
     }); 

     mediaRecorder.setCamera(camera); 
     mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); 
     mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); 
     Log.i(TAG, "a"); 

     mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); 
     mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT); 
     mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263); 
     Log.i(TAG, "b"); 

     mediaRecorder.setMaxDuration(maxDurationInMs); // set to 20000 

     String uniqueOutFile = OUTPUT_FILE + System.currentTimeMillis() + ".3gp"; 
     File outFile = new File(uniqueOutFile); 
     if (outFile.exists()) { 
      outFile.delete(); 
     } 
     mediaRecorder.setOutputFile(uniqueOutFile); 
     mediaRecorder.setVideoFrameRate(videoFramesPerSecond); // set to 20 
     mediaRecorder.setVideoSize(sView.getWidth(), sView.getHeight()); 
     Log.i(TAG, "c"); 

     mediaRecorder.setPreviewDisplay(holder.getSurface()); 
     mediaRecorder.setMaxFileSize(maxFileSizeInBytes); // set to 50000 
     mediaRecorder.prepare(); 
     Log.i(TAG, "d"); 

     mediaRecorder.start(); 
     Log.i(TAG, "e"); 

     return true; 
     } catch (IllegalStateException e) { 
      Log.i(TAG, "f"); 
      Log.e(TAG, e.getMessage()); 
      e.printStackTrace(); 
      camera.lock(); 
      return false; 
     } catch (IOException e) { 
      Log.i(TAG, "g"); 
      Log.e(TAG, e.getMessage()); 
      e.printStackTrace(); 
      camera.lock(); 
      return false; 
     } catch (RuntimeException e) { 
      Log.i(TAG, "h"); 
      Log.e(TAG, e.getMessage()); 
      camera.lock(); 
      return false; 
     } 
    } 

Todos los registros de depuración (de "a" a "d") se imprime en el registro, por lo que parece que todos los pasos upto mediaRecorder.prepare() se hacen correctamente. Luego captura un RuntimeException con el mensaje start failed: -19. Hay un question similar, pero eso no resuelve mi problema.

¿Hay alguna otra razón para obtener dicho error?

Respuesta

14

Acabamos de descubrir el error, en esta línea:

mediaRecorder.setVideoSize(sView.getWidth(), sView.getHeight()); 

después de comentar esta línea, el código funciona perfectamente!

+0

no trabajar en SAMSUNG grandes dúos – Neji

+4

Al comentar esta línea fuera Lanzará fuerza de cierre en dispositivos Samsung como GN2, GS. Esta no es una solución. Aunque no he empezado a Android por mucho tiempo, ¡estoy un poco harto de Android ahora!Simplemente dejan que los fabricantes hagan libremente los teléfonos sin el estándar. – Dante

+2

¿Cómo se puede especificar el tamaño del video si elimina esta línea? – TOP

2

he resuelto mi problema de una vez he añadido esto para grabación de vídeo

/** 
* Start video recording by cleaning the old camera preview 
*/ 
private void startVideoRecorder() { 
    // THIS IS NEEDED BECAUSE THE GLASS CURRENTLY THROWS AN ERROR OF 
    // "MediaRecorder start failed: -19" 
    // THIS WONT BE NEEDED INCASE OF PHONE AND TABLET 
    // This causes crash in glass kitkat version so remove it 
    // try { 
    // mCamera.setPreviewDisplay(null); 
    // } catch (java.io.IOException ioe) { 
    // Log.d(TAG, 
    // "IOException nullifying preview display: " 
    // + ioe.getMessage()); 
    // } 
    // mCamera.stopPreview(); 
    // mCamera.unlock(); 
    recorder = new MediaRecorder(); 
    // Let's initRecorder so we can record again 
    initRecorder(); 
} 

/** 
* Initialize video recorder to record video 
*/ 
private void initRecorder() { 
    try { 
     File dir = new File(folderPath); 
     if (!dir.exists()) { 
      dir.mkdirs(); 
     } 
     mCamera.stopPreview(); 
     mCamera.unlock(); 
     videofile = new File(dir, fileName + ".mp4"); 
     recorder.setCamera(mCamera); 

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

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

     // Step 4: Set output file 
     recorder.setOutputFile(videofile.getAbsolutePath()); 
     // Step 5: Set the preview output 
     recorder.setPreviewDisplay(mPreview.getHolder().getSurface()); 
     // Step 6: Prepare configured MediaRecorder 
     recorder.setMaxDuration(video_duration * 1000); 
     recorder.setOnInfoListener(new OnInfoListener() { 

      @Override 
      public void onInfo(MediaRecorder mr, int what, int extra) { 
       if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) { 

        mCamera.stopPreview(); 
        releaseMediaRecorder(); 

        /* 
        * initiate media scan and put the new things into the 
        * path array to make the scanner aware of the location 
        * and the files you want to see 
        */MediaScannerConnection.scanFile(
          CuxtomCamActivity.this, 
          new String[] { videofile.getPath() }, null, 
          null); 

        Intent intent = new Intent(); 
        intent.putExtra(CuxtomIntent.FILE_PATH, 
          videofile.getPath()); 
        intent.putExtra(CuxtomIntent.FILE_TYPE, FILE_TYPE.VIDEO); 
        setResult(RESULT_OK, intent); 
        finish(); 
       } 

      } 
     }); 
     recorder.prepare(); 
     recorder.start(); 
    } catch (Exception e) { 
     Log.e("Error Stating CuXtom Camera", e.getMessage()); 
    } 
} 
private void releaseMediaRecorder() { 
    if (recorder != null) { 
     recorder.reset(); // clear recorder configuration 
     recorder.release(); // release the recorder object 
     recorder = null; 
    } 
} 

Para la guía detallada referirse a este Open Source Cuxtom Cam

0

el problema está en su código setVideoSize().

y por qué este error de código ...

De la investigación que he hecho, el código de error -19 se produce cuando hay un problema con el tamaño del video según lo establecido por MediaRecorder#setVideoSize()

plazo esto código y ver générale pantalla que su cámara en su dispositivo puede soportar:

final List<Camera.Size> mSupportedVideoSizes = getSupportedVideoSizes(mCamera); 
     for (Camera.Size str : mSupportedVideoSizes) 
      Log.e(TAG, "mSupportedVideoSizes "+str.width + ":" + str.height + " ... " 
        + ((float) str.width/str.height)); 

y el método es:

public List<Size> getSupportedVideoSizes(Camera camera) { 
     if (camera.getParameters().getSupportedVideoSizes() != null) { 
      return camera.getParameters().getSupportedVideoSizes(); 
     } else { 
      // Video sizes may be null, which indicates that all the supported 
      // preview sizes are supported for video recording. 
      return camera.getParameters().getSupportedPreviewSizes(); 
     } 
    } 
0

Tuve ese problema con algunos teléfonos específicos, descubrí que no podía establecer tamaños de perfil de cámara en algunos de ellos. Pero cuando eso funcionó para los androides problemáticos dejó de funcionar en los dispositivos de trabajo anteriores.

Así que al final mi lógica implementada fue algo así como:

  • Conjunto de anchura/altura
  • intenta iniciar la grabadora Merdia
  • En caso de excepción, vuelve a intentarlo sin establecer anchura/altura

Tipo de lógica de la basura, pero funcionó.

he configurar un proyecto github con esa aplicación, probarlo: https://github.com/rafaelsilverio/MediaRecorder

Cuestiones relacionadas