草庐IT

android - 视频录制在 ICS 中不起作用

coder 2023-12-05 原文

我已经在 Android Phone 中实现了录制视频的代码。此代码适用于 2.2 、 2.3 。

但是当我 checkin ICS 代码时,代码不起作用?

我在这里发布了代码和 xml 文件。

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) {


        }
    }
}

视频记录.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>

最佳答案

这可能对你有帮助,我最近正在研究它并且可以工作,但在这里我使用的是 Intent,在这里从相机获取视频并将其写入 sdcard 文件夹并使用该路径播放这个视频。跳跃它有助于完整

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;
    }       
}

关于android - 视频录制在 ICS 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12890483/

有关android - 视频录制在 ICS 中不起作用的更多相关文章

  1. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  2. ruby-on-rails - s3_direct_upload 在生产服务器中不工作 - 2

    在Rails4.0.2中,我使用s3_direct_upload和aws-sdkgems直接为s3存储桶上传文件。在开发环境中它工作正常,但在生产环境中它会抛出如下错误,ActionView::Template::Error(noimplicitconversionofnilintoString)在View中,create_cv_url,:id=>"s3_uploader",:key=>"cv_uploads/{unique_id}/${filename}",:key_starts_with=>"cv_uploads/",:callback_param=>"cv[direct_uplo

  3. 屏幕录制为什么没声音?检查这2项,轻松解决 - 2

    相信很多人在录制视频的时候都会遇到各种各样的问题,比如录制的视频没有声音。屏幕录制为什么没声音?今天小编就和大家分享一下如何录制音画同步视频的具体操作方法。如果你有录制的视频没有声音,你可以试试这个方法。 一、检查是否打开电脑系统声音相信很多小伙伴在录制视频后会发现录制的视频没有声音,屏幕录制为什么没声音?如果当时没有打开音频录制,则录制好的视频是没有声音的。因此,建议在录制前进行检查。屏幕上没有声音,很可能是因为你的电脑系统的声音被禁止了。您只需打开电脑系统的声音,即可录制音频和图画同步视频。操作方法:步骤1:点击电脑屏幕右下侧的“小喇叭”图案,在上方的选项中,选择“声音”。 步骤2:在“声

  4. 动漫制作技巧如何制作动漫视频 - 2

    动漫制作技巧是很多新人想了解的问题,今天小编就来解答与大家分享一下动漫制作流程,为了帮助有兴趣的同学理解,大多数人会选择动漫培训机构,那么今天小编就带大家来看看动漫制作要掌握哪些技巧?一、动漫作品首先完成草图设计和原型制作。设计草图要有目的、有对象、有步骤、要形象、要简单、符合实际。设计图要一致性,以保证制作的顺利进行。二、原型制作是根据设计图纸和制作材料,可以是手绘也可以是3d软件创建。在此步骤中,要注意的问题是色彩和平面布局。三、动漫制作制作完成后,加工成型。完成不同的表现形式后,就要对设计稿进行加工处理,使加工的难易度降低,并得到一些基本准确的概念,以便于后续的大样、准确的尺寸制定。四、

  5. python ffmpeg 使用 pyav 转换 一组图像 到 视频 - 2

    2022/8/4更新支持加入水印水印必须包含透明图像,并且水印图像大小要等于原图像的大小pythonconvert_image_to_video.py-f30-mwatermark.pngim_dirout.mkv2022/6/21更新让命令行参数更加易用新的命令行使用方法pythonconvert_image_to_video.py-f30im_dirout.mkvFFMPEG命令行转换一组JPG图像到视频时,是将这组图像视为MJPG流。我需要转换一组PNG图像到视频,FFMPEG就不认了。pyav内置了ffmpeg库,不需要系统带有ffmpeg工具因此我使用ffmpeg的python包装p

  6. TimeSformer:抛弃CNN的Transformer视频理解框架 - 2

    Transformers开始在视频识别领域的“猪突猛进”,各种改进和魔改层出不穷。由此作者将开启VideoTransformer系列的讲解,本篇主要介绍了FBAI团队的TimeSformer,这也是第一篇使用纯Transformer结构在视频识别上的文章。如果觉得有用,就请点赞、收藏、关注!paper:https://arxiv.org/abs/2102.05095code(offical):https://github.com/facebookresearch/TimeSformeraccept:ICML2021author:FacebookAI一、前言Transformers(VIT)在图

  7. 安卓apk修改(Android反编译apk) - 2

    最近因为项目需要,需要将Android手机系统自带的某个系统软件反编译并更改里面某个资源,并重新打包,签名生成新的自定义的apk,下面我来介绍一下我的实现过程。APK修改,分为以下几步:反编译解包,修改,重打包,修改签名等步骤。安卓apk修改准备工作1.系统配置好JavaJDK环境变量2.需要root权限的手机(针对系统自带apk,其他软件免root)3.Auto-Sign签名工具4.apktool工具安卓apk修改开始反编译本文拿Android系统里面的Settings.apk做demo,具体如何将apk获取出来在此就不过多介绍了,直接进入主题:按键win+R输入cmd,打开命令窗口,并将路

  8. ruby-on-rails - "assigns"在 Ruby on Rails 中有什么作用? - 2

    我目前正在尝试学习RubyonRails和测试框架RSpec。assigns在此RSpec测试中做什么?describe"GETindex"doit"assignsallmymodelas@mymodel"domymodel=Factory(:mymodel)get:indexassigns(:mymodels).shouldeq([mymodel])endend 最佳答案 assigns只是检查您在Controller中设置的实例变量的值。这里检查@mymodels。 关于ruby-o

  9. ruby - 字符串文字前面的 * 在 ruby​​ 中有什么作用? - 2

    这段代码似乎创建了一个范围从a到z的数组,但我不明白*的作用。有人可以解释一下吗?[*"a".."z"] 最佳答案 它叫做splatoperator.SplattinganLvalueAmaximumofonelvaluemaybesplattedinwhichcaseitisassignedanArrayconsistingoftheremainingrvaluesthatlackcorrespondinglvalues.Iftherightmostlvalueissplattedthenitconsumesallrvaluesw

  10. ruby - 为什么这个 eval 在 Ruby 中不起作用 - 2

    你能解释一下吗?我想评估来自两个不同来源的值和计算。一个消息来源为我提供了以下信息(以编程方式):'a=2'第二个来源给了我这个表达式来评估:'a+3'这个有效:a=2eval'a+3'这也有效:eval'a=2;a+3'但我真正需要的是这个,但它不起作用:eval'a=2'eval'a+3'我想了解其中的区别,以及如何使最后一个选项起作用。感谢您的帮助。 最佳答案 您可以创建一个Binding,并将相同的绑定(bind)与每个eval相关联调用:1.9.3p194:008>b=binding=>#1.9.3p194:009>eva

随机推荐