视频录制不工作的ICS [英] Video Recording Not Working in ICS

查看:121
本文介绍了视频录制不工作的ICS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现Android手机code录制视频。这code是工作在2.2,2.3。

但是,当我在ICS code检查工作不?

在这里我贴code和xml文件。

videorecord.java

 进口的java.io.File;
进口java.io.IOException异常;


进口android.app.Activity;
进口android.app.AlertDialog;
进口android.content.Context;
进口android.content.DialogInterface;
进口android.content.Intent;
进口android.content.Shared preferences;
进口android.hardware.Camera;
进口android.media.CamcorderProfile;
进口android.media.MediaRecorder;
进口android.os.Bundle;
进口android.os.CountDownTimer;
进口android.os.Environment;
进口android.util.Log;
进口android.view.Display;
进口android.view.KeyEvent;
进口android.view.SurfaceHolder;
进口android.view.SurfaceView;
进口android.view.View;
进口android.widget.EditText;
进口android.widget.FrameLayout;
进口android.widget.ImageView;
进口android.widget.LinearLayout;
进口android.widget.TextView;
进口android.widget.Toast;

公共类videorecord延伸活动{
    共享preferences.Editor pre;
    字符串的文件名;
    CountDownTimer吨;
    私人相机myCamera;
    私人MyCameraSurfaceView myCameraSurfaceView;
    私人MediaRecorder mediaRecorder;
    整数CNT = 0;
    的LinearLayout myButton的;
    TextView的myButton1;
    SurfaceHolder surfaceHolder;
    布尔记录;
    私人TextView的txtcount;
    私人ImageView的btnplay;


    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);

        记录= FALSE;

        的setContentView(R.layout.videorecord);

        在里面();

        myCamera = getCameraInstance();
        如果(myCamera == NULL){
        }

        myCameraSurfaceView =新MyCameraSurfaceView(这一点,myCamera);
        的FrameLayout myCamera preVIEW =(的FrameLayout)findViewById(R.id.videoview);

        显示显示= getWindowManager()getDefaultDisplay()。
           INT宽度= display.getWidth();
           INT高= display.getHeight();
        myCameraSurfaceView.setLayoutParams(新LinearLayout.LayoutParams(宽度,高度-60));

        myCamera preview.addView(myCameraSurfaceView);

        myButton的=(的LinearLayout)findViewById(R.id.mybutton);
        btnplay.setOnClickListener(myButtonOnClickListener);
    }

    私人无效的init(){

        txtcount =(TextView中)findViewById(R.id.txtcounter);

        // myButton1 =(TextView中)findViewById(R.id.mybutton1);

        btnplay =(ImageView的)findViewById(R.id.btnplay);

        T =新CountDownTimer(为Long.MAX_VALUE,1000){

            @覆盖
            公共无效onTick(长millisUntilFinished){

                CNT ++;
                字符串时间=新的整数(CNT)的ToString();

                长米利斯= CNT;
                   INT秒=(INT)(米利斯/ 60);
                   INT分钟=秒/ 60;
                   秒=秒%60;

                   txtcount.setText(的String.Format(%D:%02D:%02D,分,秒,米利斯));

            }

            @覆盖
            公共无效onFinish(){}
        };
    }

    @覆盖
    公共布尔的onkeydown(INT键code,KeyEvent的事件){

         如果((钥匙code == KeyEvent.KEY code_BACK))
         {

             如果(录音)
             {
                 新AlertDialog.Builder(videorecord.this).setTitle(你想保存的视频?)
                    .setPositiveButton(OK,新DialogInterface.OnClickListener(){


                        公共无效的onClick(DialogInterface对话,诠释它){

                            文件名();
                            //完();
                        }
                    })。setNegativeButton(CANCLE,新DialogInterface.OnClickListener(){


                        公共无效的onClick(DialogInterface对话,诠释它){
                            // TODO自动生成方法存根

                        }
                    })。显示();
             }
             其他
             {
                 如果((钥匙code == KeyEvent.KEY code_BACK))
                 {
                            //意图homeIntent =新的意图(Intent.ACTION_MAIN);
                        //homeIntent.addCategory(Intent.CATEGORY_HOME);
                        //homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        // startActivity(homeIntent);

                        //this.finishActivity(1);
                     完();

                }

                 // moveTaskToBack(真正的);


            //   完();
                        返回super.onKeyDown(键code,事件);
                    }
             }
         其他
         {
            // Toast.makeText(getApplicationContext(),ASD,Toast.LENGTH_LONG).show();
             android.os.Process.killProcess(android.os.Process.myPid());
         }



        返回super.onKeyDown(键code,事件);
    }

    ImageView.OnClickListener myButtonOnClickListener
    =新ImageView.OnClickListener(){

        公共无效的onClick(视图v){




                    如果(录音){

                Log.e(中记录的错误。记录错误,);
                mediaRecorder.stop();

                t.cancel();
                文件名();
                releaseMediaRecorder();


            }其他{


                releaseCamera();

                   Log.e(中记录的错误。记录停止错误);
                //
                如果(!prepareMediaRecorder()){
                    prepareMediaRecorder();
                    完();
                }

                mediaRecorder.start();

                记录= TRUE;
            // myButton1.setText(停止录制);
            // btnplay.setImageResource(android.R.drawable.ic_media_pause);

                btnplay.setImageResource(R.drawable.sto preC);
                t.start();
            }


        }};

    私人摄像机getCameraInstance(){

        相机C = NULL;
        尝试 {
            C = Camera.open();
        }
        赶上(例外五){

        }
        返回℃;
    }

    私人无效的文件名()
    {
        AlertDialog.Builder警报=新AlertDialog.Builder(本);

        alert.setTitle(保存视频);
        alert.setMessage(输入文件名);


        最后的EditText输入=新的EditText(本);
        alert.setView(输入);

        alert.setPositiveButton(OK,新DialogInterface.OnClickListener(){
        公共无效的onClick(DialogInterface对话,诠释whichButton){
            如果(input.getText()长度()> = 1)
            {
                。文件名= input.getText()的toString();
                文件SD卡=新的文件(Environment.getExternalStorageDirectory()+/ VideoRecord);

                从=新的文件(SD卡,null.mp4)的文件;
                文件以=新的文件(SD卡,文件名+MP4。);
                from.renameTo(到);
                共享preferences SP = videorecord.this.getShared preferences(数据,MODE_WORLD_WRITEABLE);
                pre = sp.edit();
                pre.clear();
                pre.commit();
                pre.putString(lastvideo,文件名+。MP4);
                pre.commit();
                //btnplay.setImageResource(android.R.drawable.ic_media_play);
                btnplay.setImageResource(R.drawable.startrec);
            //意向意图=新的意图(videorecord.this,StopVidoWatch_Activity.class);
            // startActivity(意向);

                意图myIntent =新的意图(getApplicationContext(),StopVidoWatch_Activity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(myIntent);

            }
            其他
            {
                文件名();
            }

          }
        });

        alert.setNegativeButton(取消,新DialogInterface.OnClickListener(){
          公共无效的onClick(DialogInterface对话,诠释whichButton){

             //意向意图=新的意图(videorecord.this,StopVidoWatch_Activity.class);
            // startActivity(意向);
              档案文件=新的文件(Environment.getExternalStorageDirectory()+/VideoRecord/null.mp4);
              //布尔删除= file.delete();
              file.delete();
              完();
          }
        });

        alert.show();
    }
    私人布尔prepareMediaRecorder(){
        myCamera = getCameraInstance();
        mediaRecorder =新MediaRecorder();

        myCamera.unlock();
        mediaRecorder.setCamera(myCamera);

        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));


        文件夹=新的文件(Environment.getExternalStorageDirectory()+/ VideoRecord);

        布尔成功= FALSE;
        如果(!folder.exists()){
            成功= folder.mkdir();
        }
        如果(!成功){

        } 其他 {

        }

        mediaRecorder.setOutputFile(/ SD卡/ VideoRecord /+文件名+MP4。);

        mediaRecorder.setMaxDuration(60000);
        mediaRecorder.setMaxFileSize(5000000);

        显示显示= getWindowManager()getDefaultDisplay()。



        INT宽度= display.getHeight();
        INT高= display.getWidth();

        字符串s =新的String();
        S = s.valueOf(宽度);

        字符串S1 =新的String();
        S1 = s1.valueOf(高度);

      // Toast.makeText(videorecord.this,宽:+ S,Toast.LENGTH_LONG).show();
      // Toast.makeText(videorecord.this,身高+ S1,Toast.LENGTH_LONG).show();

        mediaRecorder.setVideoSize(高度,宽度);

        mediaRecorder.set previewDisplay(myCameraSurfaceView.getHolder()getSurface());

        尝试 {
            mediaRecorder prepare()。
        }赶上(IllegalStateException异常E){
            releaseMediaRecorder();
            返回false;
        }赶上(IOException异常E){
            releaseMediaRecorder();
            返回false;
        }
        返回true;

    }

    @覆盖
    保护无效的onPause(){
        super.onPause();
        releaseMediaRecorder();
        releaseCamera();
    }

    私人无效releaseMediaRecorder()
    {
        如果(mediaRecorder!= NULL){
            mediaRecorder.reset();
            mediaRecorder.release();
            mediaRecorder = NULL;
            myCamera.lock();
        }
    }

    私人无效releaseCamera(){
        如果(myCamera!= NULL){
            myCamera.release();
            myCamera = NULL;
        }
    }

    公共类MyCameraSurfaceView扩展了SurfaceView实现SurfaceHolder.Callback {

        私人SurfaceHolder mHolder;
        私人相机mCamera;

        公共MyCameraSurfaceView(上下文的背景下,相机摄像头){
            超(上下文);
            mCamera =摄像头;


            mHolder = getHolder();
            mHolder.addCallback(本);

            mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }


        公共无效surfaceChanged(SurfaceHolder持有人,INT格式,诠释权重,
                INT高度){

            如果(mHolder.getSurface()== NULL){

              返回;
            }


            尝试 {
                mCamera.stop preVIEW();
            }赶上(例外五){

            }

            尝试 {
                mCamera.set previewDisplay(mHolder);
                mCamera.start preVIEW();

            }赶上(例外五){
            }
        }


        公共无效surfaceCreated(SurfaceHolder持有者){
               尝试 {
                mCamera.set previewDisplay(保持器);
                mCamera.start preVIEW();
            }赶上(IOException异常E){
            }
        }


        公共无效surfaceDestroyed(SurfaceHolder持有者){


        }
    }
}
 

videorecord.xml

 < XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:方向=垂直
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =FILL_PARENT
    >

    <的FrameLayout机器人:layout_width =FILL_PARENT
    机器人:layout_height =FILL_PARENT>

    <的FrameLayout
    机器人:ID =@ + ID / videoview
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =FILL_PARENT>< /的FrameLayout>

    <的LinearLayout

       机器人:ID =@ + ID / myButton的
     机器人:layout_width =FILL_PARENT
     机器人:layout_marginBottom =0dip
    机器人:layout_height =WRAP_CONTENT机器人:方向=横向
     机器人:layout_weight =0>

<! - 
    <的TextView
       机器人:文本=开始录音
        机器人:ID =@ + ID / mybutton1
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_width =WRAP_CONTENT
        风格=@风格/ savestyle
         机器人:layout_weight =1
        机器人:重力=左

         >
         < / TextView的>
      - >
    < ImageView的机器人:layout_height =WRAP_CONTENT机器人:ID =@ + ID / btnplay
    机器人:填充=5dip
     机器人:后台=#A0000000
        机器人:文字颜色=#FFFFFFFF
        机器人:layout_width =WRAP_CONTENT机器人:SRC =@可绘制/ STARTREC/>
     < / LinearLayout中>
     <的TextView
    机器人:文本=00:00:00

    机器人:ID =@ + ID / txtcounter



          机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT

        机器人:layout_gravity =右|底

        机器人:填充=5dip

        机器人:后台=#A0000000
        机器人:文字颜色=#FFFFFFFF


     />
    < /的FrameLayout>

    < RelativeLayout的机器人:layout_width =FILL_PARENT
    机器人:layout_height =FILL_PARENT机器人:背景=@色/ BGCOLOR>


< LinearLayout中的android:layout_above =@ + ID / myButton的
    机器人:方向=横向
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =FILL_PARENT
    >


< / LinearLayout中>
< / RelativeLayout的>
< / LinearLayout中>
 

解决方案

这或许可以帮助你,我最近工作,并工作,但这里使用意向的IM,在这里得到来自摄像头的视频和SD卡的文件夹写和使用路径这部影片play.hop它有助于充分

 私人最终诠释VIDEO_RESULT = 1;

按钮btnOk =(按钮)popUpView.findViewById(R.id.btn_take_photo);
    btnOk.setOnClickListener(新OnClickListener(){
        公共无效的onClick(视图v){
            // mpopup.dismiss(); //驳回弹出
            mpopup.dismiss();
            PackageManager下午= getPackageManager();
            如果(pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)){

                尝试{
                    意图I =新的意图(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
                    //i.putExtra(MediaStore.EXTRA_OUTPUT,MyFileContentProviderVideo.CONTENT_URI);
                    startActivityForResult(ⅰ,VIDEO_RESULT);

                }赶上(例外五){

                }
            } 其他 {
                Toast.makeText(getBaseContext(),相机是不可用,Toast.LENGTH_LONG).show();
            }

        }
    });


公共无效onActivityResult(INT申请code,INT结果code,意图数据){

    selectedVideos =新的ArrayList<字符串>();

    如果(结果code == RESULT_OK和放大器;&安培;请求code == VIDEO_RESULT){
        尝试 {

            uriVideo = data.getData();
            //Toast.makeText(ProfileVideo.this,uriVideo.getPath(),Toast.LENGTH_LONG).show();

            selectedImagePath = uriVideo.getPath();
            // selectedImages =新的ArrayList<字符串>();

            byte []的BA = getCapturedVideoStream(ProfileVideo.this,数据);
            MyWrite(BA);


            // selectedImagePath = Base64.en codeBytes(BA);
            selectedVideos.add(selectedImagePath);

    }

}




公共无效MyWrite(byte []的缓冲区)
    {
        文件SD卡= Environment.getExternalStorageDirectory();
        文件目录=新的文件(sdCard.getAbsolutePath()+/ MYFILES);
        directory.mkdirs();
        //现在创建了上述目录中的文件,并写入的内容进去
        档案文件=新的文件(目录,sample.mp4);
        selectedImagePath = file.getAbsolutePath();
        FileOutputStream中FOUT = NULL;
        尝试 {
            FOUT =新的FileOutputStream(文件);
        }赶上(FileNotFoundException异常E1){
            // TODO自动生成的catch块
            e1.printStackTrace();
        }

        的BufferedOutputStream OSW =新的BufferedOutputStream(FOUT);
        尝试 {
            //osw.write(path);
            osw.write(缓冲液);
            //osw.write(buffer,偏移,长度);
        }赶上(IOException异常E){
            // TODO自动生成的catch块
            e.printStackTrace();
        }
        尝试 {
            osw.flush();
        }赶上(IOException异常E){
            // TODO自动生成的catch块
            e.printStackTrace();
        }
        尝试 {
            osw.close();
        }赶上(IOException异常E){
            // TODO自动生成的catch块
            e.printStackTrace();
        }
    }




公共静态的byte [] getCapturedVideoStream(上下文CTX,意图数据)
{
    尝试
    {
        AssetFileDescriptor videoAsset = ctx.getContentResolver()openAssetFileDescriptor(data.getData(),R)。
        的FileInputStream FIS = videoAsset.createInputStream();
        ByteArrayOutputStream BOS =新ByteArrayOutputStream();
        byte []的BUF =新的字节[1024];
        尝试
        {
            对于(INT readNum;(readNum = fis.read(BUF))= -1;!)
                bos.write(BUF,0,readNum);
        }
        赶上(IOException异常E)
        {
           // CommonFunctions.writeLOG(CacheImagesManager.class.getClass()的toString(),e.​​toString());
        }
        字节[]字节= bos.toByteArray();
        返回字节;
    }
    赶上(IOException异常E)
    {
        。//CommonFunctions.writeLOG(CacheImagesManager.class.getClass()的toString(),e.​​toString());
        返回null;
    }
}
 

I have implement code Record video in Android Phone . This code is working in 2.2 , 2.3 .

But when I checked in ICS code is not working ?

here I posted code and xml file.

videorecord.java

import java.io.File;
import java.io.IOException;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class videorecord extends Activity{
    SharedPreferences.Editor pre;
    String filename;
    CountDownTimer t;
    private Camera myCamera;
    private MyCameraSurfaceView myCameraSurfaceView;
    private MediaRecorder mediaRecorder;
    Integer cnt=0;
    LinearLayout myButton;
    TextView myButton1;
    SurfaceHolder surfaceHolder;
    boolean recording;
    private TextView txtcount;
    private ImageView btnplay;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        recording = false;

        setContentView(R.layout.videorecord);

        init();

        myCamera = getCameraInstance();
        if(myCamera == null){
        }

        myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera);
        FrameLayout myCameraPreview = (FrameLayout)findViewById(R.id.videoview);

        Display display = getWindowManager().getDefaultDisplay(); 
           int width = display.getWidth();
           int height = display.getHeight();
        myCameraSurfaceView.setLayoutParams(new LinearLayout.LayoutParams(width, height-60));

        myCameraPreview.addView(myCameraSurfaceView);

        myButton = (LinearLayout)findViewById(R.id.mybutton);
        btnplay.setOnClickListener(myButtonOnClickListener);
    }

    private void init() {

        txtcount = (TextView) findViewById(R.id.txtcounter);

        //myButton1 = (TextView) findViewById(R.id.mybutton1);

        btnplay = (ImageView)findViewById(R.id.btnplay);

        t = new CountDownTimer( Long.MAX_VALUE , 1000) {

            @Override
            public void onTick(long millisUntilFinished) {

                cnt++;
                String time = new Integer(cnt).toString();

                long millis = cnt;
                   int seconds = (int) (millis / 60);
                   int minutes = seconds / 60;
                   seconds     = seconds % 60;

                   txtcount.setText(String.format("%d:%02d:%02d", minutes, seconds,millis));

            }

            @Override
            public void onFinish() {            }
        };
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

         if ((keyCode == KeyEvent.KEYCODE_BACK)) 
         {

             if(recording)
             {
                 new AlertDialog.Builder(videorecord.this).setTitle("Do you want to save Video ?")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {


                        public void onClick(DialogInterface dialog, int which) {

                            filename();
                            //finish();
                        }
                    }).setNegativeButton("Cancle", new DialogInterface.OnClickListener() {


                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub

                        }
                    }).show();
             }
             else
             {
                 if ((keyCode == KeyEvent.KEYCODE_BACK))
                 {
                            //Intent homeIntent= new Intent(Intent.ACTION_MAIN);
                        //homeIntent.addCategory(Intent.CATEGORY_HOME);
                        //homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        //startActivity(homeIntent);

                        //this.finishActivity(1);
                     finish();

                }

                 //moveTaskToBack(true);


            //   finish();
                        return super.onKeyDown(keyCode, event);
                    }
             }
         else
         {
            // Toast.makeText(getApplicationContext(), "asd", Toast.LENGTH_LONG).show();
             android.os.Process.killProcess(android.os.Process.myPid()) ;
         }



        return super.onKeyDown(keyCode, event);
    }

    ImageView.OnClickListener myButtonOnClickListener
    = new ImageView.OnClickListener(){

        public void onClick(View v) {




                    if(recording){

                Log.e("Record error", "error in recording .");   
                mediaRecorder.stop();  

                t.cancel();
                filename();
                releaseMediaRecorder(); 


            }else{


                releaseCamera();

                   Log.e("Record Stop error", "error in recording .");
                //
                if(!prepareMediaRecorder()){
                    prepareMediaRecorder();
                    finish();
                }

                mediaRecorder.start();

                recording = true;
            //  myButton1.setText("STOP Recording");
            //  btnplay.setImageResource(android.R.drawable.ic_media_pause);

                btnplay.setImageResource(R.drawable.stoprec);
                t.start();
            }


        }};

    private Camera getCameraInstance(){

        Camera c = null;
        try {
            c = Camera.open(); 
        }
        catch (Exception e){

        }
        return c; 
    }

    private void filename()
    {
        AlertDialog.Builder alert = new AlertDialog.Builder(this);

        alert.setTitle("Save Video");
        alert.setMessage("Enter File Name");


        final EditText input = new EditText(this);
        alert.setView(input);

        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            if(input.getText().length()>=1)
            {
                filename = input.getText().toString();
                File sdcard = new File(Environment.getExternalStorageDirectory() + "/VideoRecord");

                File from = new File(sdcard,"null.mp4");
                File to = new File(sdcard,filename+".mp4");
                from.renameTo(to);
                SharedPreferences sp = videorecord.this.getSharedPreferences("data", MODE_WORLD_WRITEABLE);
                pre = sp.edit();
                pre.clear();
                pre.commit();
                pre.putString("lastvideo", filename+".mp4");
                pre.commit();
                //btnplay.setImageResource(android.R.drawable.ic_media_play);
                btnplay.setImageResource(R.drawable.startrec);
            //  Intent intent = new Intent(videorecord.this,StopVidoWatch_Activity.class);
            //  startActivity(intent);

                Intent myIntent = new Intent(getApplicationContext(), StopVidoWatch_Activity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(myIntent);

            }
            else
            {
                filename();
            }

          }
        });

        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton) {

             // Intent intent = new Intent(videorecord.this,StopVidoWatch_Activity.class);
            //  startActivity(intent);
              File file = new File(Environment.getExternalStorageDirectory() + "/VideoRecord/null.mp4");
              //boolean deleted = file.delete();
              file.delete();
              finish();
          }
        });

        alert.show();
    }
    private boolean prepareMediaRecorder(){
        myCamera = getCameraInstance();
        mediaRecorder = new MediaRecorder();

        myCamera.unlock();
        mediaRecorder.setCamera(myCamera);

        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));


        File folder = new File(Environment.getExternalStorageDirectory() + "/VideoRecord");

        boolean success = false;
        if (!folder.exists()) {
            success = folder.mkdir();
        }
        if (!success) {

        } else {

        }

        mediaRecorder.setOutputFile("/sdcard/VideoRecord/"+filename+".mp4");

        mediaRecorder.setMaxDuration(60000); 
        mediaRecorder.setMaxFileSize(5000000); 

        Display display = getWindowManager().getDefaultDisplay();



        int width = display.getHeight();
        int height = display.getWidth();

        String s = new String();
        s= s.valueOf(width);

        String s1 = new String();
        s1= s1.valueOf(height);

      //  Toast.makeText(videorecord.this, "Width : " + s , Toast.LENGTH_LONG).show();
      //  Toast.makeText(videorecord.this, "Height : " +  s1 , Toast.LENGTH_LONG).show();

        mediaRecorder.setVideoSize(height, width);

        mediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder().getSurface());

        try {
            mediaRecorder.prepare();
        } catch (IllegalStateException e) {
            releaseMediaRecorder();
            return false;
        } catch (IOException e) {
            releaseMediaRecorder();
            return false;
        }
        return true;

    }

    @Override
    protected void onPause() {
        super.onPause();
        releaseMediaRecorder();    
        releaseCamera();           
    }

    private void releaseMediaRecorder()
    {
        if (mediaRecorder != null) {
            mediaRecorder.reset();   
            mediaRecorder.release(); 
            mediaRecorder = null;
            myCamera.lock();           
        }
    }

    private void releaseCamera(){
        if (myCamera != null){
            myCamera.release();      
            myCamera = null;
        }
    }

    public class MyCameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{

        private SurfaceHolder mHolder;
        private Camera mCamera;

        public MyCameraSurfaceView(Context context, Camera camera) {
            super(context);
            mCamera = camera;


            mHolder = getHolder();
            mHolder.addCallback(this);

            mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }


        public void surfaceChanged(SurfaceHolder holder, int format, int weight,
                int height) {

            if (mHolder.getSurface() == null){

              return;
            }


            try {
                mCamera.stopPreview();
            } catch (Exception e){

            }

            try {
                mCamera.setPreviewDisplay(mHolder);
                mCamera.startPreview();

            } catch (Exception e){
            }
        }


        public void surfaceCreated(SurfaceHolder holder) {
               try {
                mCamera.setPreviewDisplay(holder);
                mCamera.startPreview();
            } catch (IOException e) {
            }
        }


        public void surfaceDestroyed(SurfaceHolder holder) {


        }
    }
}

videorecord.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    >

    <FrameLayout android:layout_width="fill_parent" 
    android:layout_height="fill_parent" >

    <FrameLayout 
    android:id="@+id/videoview" 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"></FrameLayout>

    <LinearLayout 

       android:id="@+id/mybutton" 
     android:layout_width="fill_parent" 
     android:layout_marginBottom="0dip" 
    android:layout_height="wrap_content" android:orientation="horizontal"
     android:layout_weight="0" >

<!-- 
    <TextView  
       android:text="START Recording"
        android:id="@+id/mybutton1"
        android:layout_height="wrap_content" 
        android:layout_width="wrap_content"
        style="@style/savestyle"
         android:layout_weight="1"
        android:gravity="left"

         >
         </TextView>
     -->
    <ImageView   android:layout_height="wrap_content" android:id="@+id/btnplay"
    android:padding="5dip"
     android:background="#A0000000"
        android:textColor="#ffffffff"
        android:layout_width="wrap_content" android:src="@drawable/startrec" />
     </LinearLayout>
     <TextView 
    android:text="00:00:00"

    android:id="@+id/txtcounter"



          android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 

        android:layout_gravity="right|bottom"

        android:padding="5dip"

        android:background="#A0000000"
        android:textColor="#ffffffff"


     />
    </FrameLayout>

    <RelativeLayout android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:background="@color/bgcolor" >


<LinearLayout android:layout_above="@+id/mybutton"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >


</LinearLayout>
</RelativeLayout>
</LinearLayout>

解决方案

this may helps you,i have recently working on it and works but here i m using Intent, here getting video from Camera and write it in sdcard folder and using that path this video play.hop it helps full

private final int VIDEO_RESULT = 1;

Button btnOk = (Button) popUpView.findViewById(R.id.btn_take_photo);
    btnOk.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            // mpopup.dismiss(); //dismissing the popup
            mpopup.dismiss();
            PackageManager pm = getPackageManager();
            if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {

                try{
                    Intent i = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
                    //i.putExtra(MediaStore.EXTRA_OUTPUT,MyFileContentProviderVideo.CONTENT_URI);
                    startActivityForResult(i, VIDEO_RESULT);

                }catch(Exception e){

                }                   
            } else {
                Toast.makeText(getBaseContext(), "Camera is not available",Toast.LENGTH_LONG).show();
            }

        }
    });


public void onActivityResult(int requestCode, int resultCode, Intent data) {

    selectedVideos = new ArrayList<String>();       

    if (resultCode == RESULT_OK && requestCode == VIDEO_RESULT) {
        try {           

            uriVideo = data.getData();
            //Toast.makeText(ProfileVideo.this,uriVideo.getPath(), Toast.LENGTH_LONG).show();

            selectedImagePath = uriVideo.getPath();
            //selectedImages = new ArrayList<String>();

            byte[] ba = getCapturedVideoStream(ProfileVideo.this, data);
            MyWrite(ba);


            //selectedImagePath = Base64.encodeBytes(ba);           
            selectedVideos.add(selectedImagePath);

    }       

}




public void MyWrite(byte[] buffer)
    {       
        File sdCard = Environment.getExternalStorageDirectory();
        File directory = new File (sdCard.getAbsolutePath() + "/MyFiles");
        directory.mkdirs();
        //Now create the file in the above directory and write the contents into it
        File file = new File(directory, "sample.mp4");      
        selectedImagePath = file.getAbsolutePath();     
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(file);
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        BufferedOutputStream osw = new BufferedOutputStream(fOut);
        try {
            //osw.write(path);
            osw.write(buffer);
            //osw.write(buffer, offset, length);            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            osw.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            osw.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       
    }




public static byte[] getCapturedVideoStream(Context ctx, Intent data)
{       
    try 
    {
        AssetFileDescriptor videoAsset = ctx.getContentResolver().openAssetFileDescriptor(data.getData(), "r");
        FileInputStream fis = videoAsset.createInputStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        try 
        {
            for (int readNum; (readNum = fis.read(buf)) != -1;)                
                bos.write(buf, 0, readNum);
        } 
        catch (IOException e) 
        {
           // CommonFunctions.writeLOG(CacheImagesManager.class.getClass().toString(), e.toString());
        }
        byte[] bytes = bos.toByteArray();
        return bytes;
    } 
    catch (IOException e) 
    {
        //CommonFunctions.writeLOG(CacheImagesManager.class.getClass().toString(), e.toString());
        return null;
    }       
}

这篇关于视频录制不工作的ICS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆