在 android 上捕获视频给出运行时异常启动失败:-19 在 -版本 4.0.1 Galaxy S 2 上



Update1:现在代码在将代码更改为下面后会出现此错误:

02-20 10:43:13.624: W/System.err(5494): java.lang.RuntimeException: start failed.
02-20 10:43:13.624: W/System.err(5494):     at android.media.MediaRecorder.start(Native Method)
02-20 10:43:13.624: W/System.err(5494):     at fun.audios.maker.VideoRecorderActivity.startRecording(VideoRecorderActivity.java:237)
02-20 10:43:13.624: W/System.err(5494):     at fun.audios.maker.VideoRecorderActivity.access$9(VideoRecorderActivity.java:146)
02-20 10:43:13.624: W/System.err(5494):     at fun.audios.maker.VideoRecorderActivity$1.onClick(VideoRecorderActivity.java:88)
02-20 10:43:13.624: W/System.err(5494):     at android.view.View.performClick(View.java:3620)
02-20 10:43:13.624: W/System.err(5494):     at android.widget.CompoundButton.performClick(CompoundButton.java:107)
02-20 10:43:13.624: W/System.err(5494):     at android.view.View$PerformClick.run(View.java:14292)
02-20 10:43:13.624: W/System.err(5494):     at android.os.Handler.handleCallback(Handler.java:605)
02-20 10:43:13.624: W/System.err(5494):     at android.os.Handler.dispatchMessage(Handler.java:92)
02-20 10:43:13.624: W/System.err(5494):     at android.os.Looper.loop(Looper.java:137)
02-20 10:43:13.624: W/System.err(5494):     at android.app.ActivityThread.main(ActivityThread.java:4512)
02-20 10:43:13.624: W/System.err(5494):     at java.lang.reflect.Method.invokeNative(Native Method)
02-20 10:43:13.624: W/System.err(5494):     at java.lang.reflect.Method.invoke(Method.java:511)
02-20 10:43:13.624: W/System.err(5494):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:982)
02-20 10:43:13.624: W/System.err(5494):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:749)
02-20 10:43:13.624: W/System.err(5494):     at dalvik.system.NativeStart.main(Native Method)

代码更改为:

  private void startRecording()  
   {
    mrec = new MediaRecorder(); 
     mCamera.unlock();
     mrec.setCamera(mCamera); 
     mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
     mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
     mrec.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
     mrec.setVideoFrameRate(15); //this line removed comment
     mrec.setVideoSize(720, 480);
     Method[] methods =   mrec.getClass().getMethods();
     for (Method method: methods){
            try
            {
                if(method.getName().equals("setAudioEncodingBitRate"))
                {
                   method.invoke(mrec,12200);
                }
                else if(method.getName().equals("setVideoEncodingBitRate"))
                {
                    method.invoke(mrec, 3000000);
                }
                else if(method.getName().equals("setAudioSamplingRate"))
                {
                    method.invoke(mrec,8000);
                }
                else if(method.getName().equals("setVideoFrameRate"))
                {
                    method.invoke(mrec,24);
                }
            }
            catch (IllegalArgumentException e) 
            {
                e.printStackTrace();
            } 
            catch (IllegalAccessException e) 
            {
                e.printStackTrace();
            } 
            catch (InvocationTargetException e) 
            {
                e.printStackTrace();
            }
            catch (RuntimeException e) 
             {
                Log.d("errorrrrrrrrr runtime111111111", "okkkkkkkkkk");
                e.printStackTrace();
             }
        }
     mrec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
     mrec.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
     mrec.setPreviewDisplay(surfaceHolder.getSurface());   
     mrec.setOrientationHint(90); 
     mrec.setOutputFile(Videopath);
     try 
     {
         mrec.prepare();
     } 
     catch (IllegalStateException e) 
     {
       //  releaseRecorder();
      //   return false;
     } 
     catch (IOException e) 
     {
      //   releaseRecorder();
       //  return false;
     }
     catch (RuntimeException e) 
     {
        e.printStackTrace();
     }
     catch(Exception e)
     {
      //  return false;
     }

     try
     {
         mrec.start(); 
     }
     catch (RuntimeException e) 
     {
        Log.d("errorrrrrrrrr runtime44444444444", "okkkkkkkkkk");
        e.printStackTrace();
     }
     catch(Exception e)
     {
      //  return false;
        Log.d("errorrrrrrrrr 33333333333", "okkkkkkkkkk");
     }
     isRecording=true;
    // return true;
 }

允许者像这样添加:

       <uses-permission android:name="android.permission.CAMERA" />
       <uses-feature android:name="android.hardware.camera" />
       <uses-feature android:name="android.hardware.screen.portrait" />
       <uses-permission android:name="android.permission.RECORD_AUDIO" />
       <uses-feature android:name="android.hardware.camera.autofocus" />
       <uses-permission android:name="android.permission.RECORD_VIDEO"/>
       <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
     <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>this is my 
//

/我是安卓新手,有这个代码来捕获视频.大部分代码是根据相机中的安卓开发人员指南用户。但是给了我异常运行时异常:无法连接到相机服务。我的哪一行代码有错误?整个日志在这里:

02-20 05:42:56.054: W/System.err(4991): java.lang.RuntimeException: Fail to connect to camera service
W/System.err(4991):     at android.hardware.Camera.native_setup(Native Method)
02-20 05:42:56.054: W/System.err(4991):     at android.hardware.Camera.<init>(Camera.java:344)
02-20 05:42:56.054: W/System.err(4991):     at android.hardware.Camera.open(Camera.java:321)
02-20 05:42:56.054: W/System.err(4991):     at fun.audios.maker.VideoRecorderActivity.startRecording(VideoRecorderActivity.java:144)
02-20 05:42:56.054: W/System.err(4991):     at fun.audios.maker.VideoRecorderActivity.access$9(VideoRecorderActivity.java:142)
02-20 05:42:56.054: W/System.err(4991):     at fun.audios.maker.VideoRecorderActivity$1.onClick(VideoRecorderActivity.java:86)
02-20 05:42:56.054: W/System.err(4991):     at android.view.View.performClick(View.java:3620)
02-20 05:42:56.054: W/System.err(4991):     at android.widget.CompoundButton.performClick(CompoundButton.java:107)
02-20 05:42:56.054: W/System.err(4991):     at android.view.View$PerformClick.run(View.java:14292)
02-20 05:42:56.054: W/System.err(4991):     at android.os.Handler.handleCallback(Handler.java:605)
02-20 05:42:56.054: W/System.err(4991):     at android.os.Handler.dispatchMessage(Handler.java:92)
02-20 05:42:56.054: W/System.err(4991):     at android.os.Looper.loop(Looper.java:137)
02-20 05:42:56.054: W/System.err(4991):     at android.app.ActivityThread.main(ActivityThread.java:4512)
02-20 05:42:56.054: W/System.err(4991):     at java.lang.reflect.Method.invokeNative(Native Method)
02-20 05:42:56.054: W/System.err(4991):     at java.lang.reflect.Method.invoke(Method.java:511)
02-20 05:42:56.054: W/System.err(4991):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:982)
02-20 05:42:56.054: W/System.err(4991):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:749)
02-20 05:42:56.054: W/System.err(4991):     at dalvik.system.NativeStart.main(Native Method)
02-20 05:42:56.054: D/errorrrrrrrrr runtime(4991): okkkkkkkkkk

这是我的代码:

public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recorder_video);
        InitializeUI();
//button for start and stop recording calls
}

private void startRecording()  
{
    //mCamera = getCameraInstance();
    mrec = new MediaRecorder(); 
     mCamera.unlock();
     mrec.setCamera(mCamera); 
     mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
     mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
     mrec.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
   //  mrec.setVideoFrameRate(15);
     mrec.setVideoSize(720, 480);
     Method[] methods =   mrec.getClass().getMethods();
     for (Method method: methods){
            try
            {
                if(method.getName().equals("setAudioEncodingBitRate"))
                {
                   method.invoke(mrec,12200);
                }
                else if(method.getName().equals("setVideoEncodingBitRate"))
                {
                    method.invoke(mrec, 3000000);
                }
                else if(method.getName().equals("setAudioSamplingRate"))
                {
                    method.invoke(mrec,8000);
                }
                else if(method.getName().equals("setVideoFrameRate"))
                {
                    method.invoke(mrec,24);
                }
            }
            catch (IllegalArgumentException e) 
            {
                e.printStackTrace();
            } 
            catch (IllegalAccessException e) 
            {
                e.printStackTrace();
            } 
            catch (InvocationTargetException e) 
            {
                e.printStackTrace();
            }
            catch (RuntimeException e) 
             {
                Log.d("errorrrrrrrrr runtime111111111", "okkkkkkkkkk");
                e.printStackTrace();
             }
        }
     mrec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
     mrec.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
     mrec.setPreviewDisplay(surfaceHolder.getSurface());   
     mrec.setOrientationHint(90); 
     mrec.setOutputFile(Videopath);
     try 
     {
         mrec.prepare();
     } 
     catch (IllegalStateException e) 
     {
       //  releaseRecorder();
      //   return false;
     } 
     catch (IOException e) 
     {
      //   releaseRecorder();
       //  return false;
     }
     catch (RuntimeException e) 
     {
        e.printStackTrace();
     }
     catch(Exception e)
     {
      //  return false;
     }

     try
     {
         mrec.start(); 
     }
     catch (RuntimeException e) 
     {
        Log.d("errorrrrrrrrr runtime44444444444", "okkkkkkkkkk");
        e.printStackTrace();
     }
     catch(Exception e)
     {
      //  return false;
        Log.d("errorrrrrrrrr 33333333333", "okkkkkkkkkk");
     }
     isRecording=true;
    // return true;
 }
 //-------------------------------------------------------------
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance()
{
    Camera c = null;
    try 
    {
        c = Camera.open(); // attempt to get a Camera instance
    }
    catch (Exception e){
        // Camera is not available (in use or does not exist)
    }
    return c; // returns null if camera is unavailable
}
//-------------------------------------------------------------
private void stopRecording() 
{
    if(isRecording)
    {
    mrec.stop();  // stop the recording
    releaseRecorder(); // release the MediaRecorder object
    btnlistToggle.setEnabled(true);
    isRecording=false;
    }
}
//-------------------------------------------------------------
// release the recorder after recording
    private void releaseRecorder() 
    {
        if (mrec != null) {
            mrec.reset();   // clear recorder configuration
            mrec.release(); // release the recorder object
            mrec = null;
            mCamera.lock();           // lock camera for later use
        }
   }
//-------------------------------------------------------------
    // release the camera after recording
    private void releaseCamera() 
    {
         if (mCamera != null)
         {
             mCamera.release();        // release the camera for other applications
             mCamera = null;
         }
    }
     public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height) 
{
    // If your preview can change or rotate, take care of those events here.
    // Make sure to stop the preview before resizing or reformatting it.
    if (holder.getSurface() == null)
    {
      // preview surface does not exist
      return;
    }
    // stop preview before making changes
    try 
    {
        mCamera.stopPreview();
    } 
    catch (Exception e)
    {
      // ignore: tried to stop a non-existent preview
    }
    // set preview size and make any resize, rotate or
    // reformatting changes here
    // start preview with new settings
    try 
    {
        mCamera.setPreviewDisplay(holder);
        mCamera.startPreview();
    } 
    catch (Exception e)
    {
      //  Log.d(TAG, "Error starting camera preview: " + e.getMessage());
    }
}
 //-------------------------------------------------------------
@Override
public void surfaceCreated(SurfaceHolder holder) 
{
     if (mCamera != null)
       {
          Parameters params = mCamera.getParameters();
          mCamera.setParameters(params);
          mCamera.setDisplayOrientation(90);
          try 
          {
             mCamera .setPreviewDisplay(holder);
             mCamera .startPreview();
           } 
          catch (IOException e) 
          {
            e.printStackTrace();
          }
       }
       else
       {
          Toast.makeText(getApplicationContext(), "Camera not available!", Toast.LENGTH_LONG).show();
         VideoRecorderActivity.this.finish();
       }

}
 //-------------------------------------------------------------
@Override
public void surfaceDestroyed(SurfaceHolder holder) 
{
}
      protected void onPause() 
 {
    datasource.close();
    super.onPause();
    //if(mrec != null)
    //{
      releaseRecorder();       // if you are using MediaRecorder, release it first
      releaseCamera();              // release the camera immediately on pause event
    //}
}
 private void InitializeUI()
 {

       // Create an instance of Camera
        mCamera = Camera.open();
        mCamera.lock();
        surfaceView = (SurfaceView) findViewById(R.id.surface_camera);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mToggleButton = (ToggleButton) findViewById(R.id.toggleRecordingButton);
 }

这是我的XML布局。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" 
    android:layout_gravity="center_horizontal">
            <LinearLayout 
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" 
              android:orientation="vertical" 
              android:layout_gravity="center_horizontal" android:background="@drawable/bg_header_footers">
              <LinearLayout 
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" 
                android:layout_gravity="center_horizontal" android:paddingTop="2dp">
                   <TextView
                        android:id="@+id/tvSetNameRecorder"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:textColor="@color/White"
                        android:textSize="18dp"
                        android:textStyle="bold" 
                        android:text="Make your Video!" 
                        android:layout_gravity="center"/>
             </LinearLayout>
              <LinearLayout 
                  android:orientation="horizontal"
                  android:layout_width="wrap_content" 
                  android:layout_height="wrap_content" android:layout_gravity="center_horizontal">  
                  <LinearLayout
                    android:layout_width="wrap_content" 
                    android:layout_height="wrap_content" >       
                    <TextView
                        android:id="@+id/tvTimer1"
                        android:layout_width="wrap_content"
                        android:layout_height="fill_parent"
                        android:gravity="center"
                         android:textColor="@color/Lightgray"
                        android:textAppearance="?android:attr/textAppearanceLarge"
                        android:textStyle="bold" 
                        android:text="00:00:00"/>                  
                     </LinearLayout>    
                  <LinearLayout
                       android:layout_width="wrap_content" 
                       android:layout_height="wrap_content" 
                       android:paddingLeft="10dp">     
                    <ImageView
                           android:id="@+id/imgcheshmak1"
                           android:layout_width="wrap_content"
                           android:layout_height="wrap_content"
                           android:src="@drawable/cheshmak" 
                           android:visibility="gone"/>
                    </LinearLayout> 
            </LinearLayout>
         </LinearLayout>
            <LinearLayout 
                 android:layout_width="match_parent"
                android:layout_height="match_parent" 
                android:layout_weight="1">
              <SurfaceView
                android:id="@+id/surface_camera"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>
            </LinearLayout>

            <TableLayout
                    android:gravity="center_horizontal" 
                    android:id="@+id/linerlistandback"
                     android:layout_width="match_parent"
                     android:layout_gravity="center" 
                     android:layout_centerHorizontal="true" 
                     android:layout_height="wrap_content">  
                    <TableRow 
                         android:layout_gravity="center_horizontal" 
                         android:gravity="center" 
                         android:layout_height="wrap_content" 
                         android:layout_width="match_parent">
                         <LinearLayout 
                              android:layout_height="wrap_content" 
                              android:layout_width="0dp" android:layout_weight="1" android:paddingRight="2dp">   
                           <Button
                               android:id="@+id/btnToggleListVideo"
                               android:layout_width="0dp"
                               android:layout_height="40dp"
                               android:background="@drawable/selector_button"
                               android:drawableLeft="@drawable/listtttt" 
                               android:paddingLeft="30dp" 
                               android:paddingRight="20dp" 
                               android:layout_weight="1" 
                               android:textSize="20dp" android:text="List"/>
                         </LinearLayout>
                         <LinearLayout
                             android:layout_height="wrap_content" 
                             android:layout_width="0dp" 
                             android:layout_weight="1" android:paddingLeft="2dp">
                             <ToggleButton
                                 android:id="@+id/toggleRecordingButton"
                                 android:layout_width="0dp"
                                 android:textOff="Start"
                                 android:textOn="Stop" 
                                 android:background="@drawable/selector_button" 
                                 android:layout_height="40dp" 
                                 android:drawableLeft="@drawable/camera" 
                                 android:paddingLeft="30dp" 
                                 android:paddingRight="20dp" android:layout_weight="1" android:textSize="20dp"/>
                         </LinearLayout>
                      </TableRow>
                </TableLayout>
</LinearLayout>

我想知道您是否添加了适当的权限。您必须在Menifest中添加权限

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />

使用相机时,如果相机与其他应用程序连接,则无法使用相机(可能会导致无法连接相机服务)。

因此,您必须确保只有您的应用程序使用相机服务

我希望你能纠正你的错误

再见!

根据您的崩溃日志

02-20 05:42:56.054: W/System.err(4991): java.lang.RuntimeException: Fail to connect to camera service
W/System.err(4991):     at android.hardware.Camera.native_setup(Native Method)
02-20 05:42:56.054: W/System.err(4991):     at android.hardware.Camera.<init>(Camera.java:344)
02-20 05:42:56.054: W/System.err(4991):     at android.hardware.Camera.open(Camera.java:321)
02-20 05:42:56.054: W/System.err(4991):     at fun.audios.maker.VideoRecorderActivity.startRecording(VideoRecorderActivity.java:144)

,则无法在媒体录像机中成功打开摄像机。

您可以阅读安卓教程 - 捕获视频法典:

private boolean prepareVideoRecorder(){
    mCamera = getCameraInstance();
    mMediaRecorder = new MediaRecorder();
    // Step 1: Unlock and set camera to MediaRecorder
    mCamera.unlock();
    mMediaRecorder.setCamera(mCamera);
    // Step 2: Set sources
    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
    // Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
    mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
    // Step 4: Set output file
    mMediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO).toString());
    // Step 5: Set the preview output
    mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
    // Step 6: Prepare configured MediaRecorder
    try {
        mMediaRecorder.prepare();
    } catch (IllegalStateException e) {
        Log.d(TAG, "IllegalStateException preparing MediaRecorder: " + e.getMessage());
        releaseMediaRecorder();
        return false;
    } catch (IOException e) {
        Log.d(TAG, "IOException preparing MediaRecorder: " + e.getMessage());
        releaseMediaRecorder();
        return false;
    }
    return true;
}

如果代码无法正常工作,则应该是您的ROM问题。

您似乎没有使用相机服务的正确权限。尝试将其添加到清单文件中:

编辑:它对我有用!我使用了与您相同的代码,我知道我以前说过,但请检查您的权限:

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.screen.portrait" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />

最后我找到了解决方案。我删除了一部分代码,然后启动失败错误没有发生。我将代码更改为:

private void startRecording()  
    {
         mrec = new MediaRecorder(); 
         mCamera.unlock();
         mrec.setCamera(mCamera); 
         mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
         mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
         mrec.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
         mrec.setVideoFrameRate(15);
         mrec.setVideoSize(720, 480);
         mrec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
         mrec.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
         mrec.setPreviewDisplay(surfaceHolder.getSurface());   
         mrec.setOrientationHint(90); 
         mrec.setOutputFile(Videopath);
         try 
         {
             mrec.prepare();
             mrec.start(); 
         } 
         catch (IllegalStateException e) 
         {
           //  releaseRecorder();
          //   return false;
         } 
         catch (IOException e) 
         {
          //   releaseRecorder();
           //  return false;
         }
         catch (RuntimeException e) 
         {
            e.printStackTrace();
         }
         catch(Exception e)
         {
          //  return false;
         }
     }

我想调用方法的参数值在设置时有问题。如果你有一些更好的反应旋转,使质量更好,比如我的调用方法,请发布你的回复,以帮助我和其他人阅读这篇文章。

最新更新