Android MediaRecorder – "inicio fallido: -19"
Estoy tratando de crear una grabadora de video en Android, y he preparado mi código que se supone que está funcionando – pero constantemente obtener un error de start failed: -19
mensaje de error start failed: -19
.
Aquí está mi código:
- Mi declaración de "devolución" no funciona incluso cuando no hay otras ramas de código
- MediaRecorder para grabar los últimos X segundos
- Error al iniciar MediaRecorder: -38
- Grabación de llamadas - hacer que funcione en Nexus 5X (posible ROM o ROM personalizado)
- Cómo leer la longitud del video grabado con MediaRecorder en el directorio privado de almacenamiento de aplicaciones construido mediante context.getFilesDir ()?
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 imprimen en el registro, por lo que parece que todos los pasos hasta mediaRecorder.prepare()
se realizan correctamente. A continuación, captura una RuntimeException
con error de start failed: -19
mensaje start failed: -19
. Hay una pregunta similar, pero eso no soluciona mi problema.
¿Hay alguna otra razón para obtener tal error?
- No se puede realizar descodificación de bajo nivel de vídeo en Android 4.2 sin utilizar extractor de medios
- Android captura de vídeo de cámara lenta con CamcorderProfile
- Libstreaming errores (búfer de decodificador no lo suficientemente grande, decodificador no decodificar nada)
- Android Media Recorder no graba videos largos en Google Glass
- No se puede grabar vídeo y tomar fotogramas de la función de devolución de un elemento de visualización al mismo tiempo
- ¿Calidad de video en android?
- No se puede registrar la llamada usando MediaRecorder
- Java.lang.IllegalStateException en android.media.MediaRecorder.start al llamar a MediaRecorder.start en onLongClickListener
Acabo 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!
He resuelto mi problema una vez que he añadido esto para la 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 obtener una guía detallada, consulte este Open Source Cuxtom Cam
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 vídeo según lo establecido por MediaRecorder#setVideoSize()
Ejecutar este código, y ver la pantalla whitch que su cámara en su dispositivo puede admitir:
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(); } }
Tuve ese problema con algunos teléfonos específicos, he descubierto que no pude establecer los tamaños de perfil de camcoder en algunos de ellos. Pero cuando eso funcionó para los androides problemáticos dejó de trabajar en los dispositivos de trabajo anteriores.
Así que al final mi lógica implementada fue algo como:
- Ajustar anchura / altura
- Intente iniciar el grabador de merdia
- En caso de excepción, intente de nuevo sin ajustar el ancho / altura
Una especie de lógica de basura, pero eso funcionó.
He configurado un proyecto github con esa implementación, pruébelo: https://github.com/rafaelsilverio/MediaRecorder
- AdMob: versión actualizada de la solución de problemas de la identificación de anuncios de AdMob
- Barra de progreso vertical en android