在 Android 中录制、保存和播放视频

Posted

技术标签:

【中文标题】在 Android 中录制、保存和播放视频【英文标题】:Record, save and play a video in Android 【发布时间】:2012-05-03 23:10:19 【问题描述】:

我正在尝试制作一个使用相机应用程序录制视频的应用程序,然后将该视频保存在 SD 卡上以便我可以播放它。我有一些代码,但我不知道如何继续,因为我是 android 的初学者。

我的活动:

public class Camcorder extends Activity 

     private CamcorderView camcorderView; 
     private boolean recording = false; 

     /** Called when the activity is first created. */ 
     @Override 
     public void onCreate(Bundle savedInstanceState)  
          super.onCreate(savedInstanceState);
          //irrelevant code

          camcorderView = (CamcorderView) findViewById(R.id.camcorder_preview); 
      

     @Override 
     public boolean onKeyDown(int keyCode, KeyEvent event) 
      
         if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) 
          
          if (recording)  
                camcorderView.stopRecording();
                finish(); 
             else  
                recording = true; 
                camcorderView.startRecording(); 
             
             return true; 
          
         return super.onKeyDown(keyCode, event); 
            

CamcorderView 类:

public class CamcorderView extends SurfaceView implements
    SurfaceHolder.Callback 

MediaRecorder recorder;
SurfaceHolder holder;
String outputFile = "/sdcard/default.mp4";

public CamcorderView(Context context, AttributeSet attrs) 
    super(context, attrs);

    holder = getHolder();
    holder.addCallback(this);
    holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    recorder = new MediaRecorder();
    recorder.setAudiosource(MediaRecorder.AudioSource.MIC);
    recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
    recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
    // recorder.setVideoSize(480, 320);
    // recorder.setVideoFrameRate(15);
    // recorder.setMaxDuration(10000);


public void surfaceCreated(SurfaceHolder holder) 
    recorder.setOutputFile(outputFile);
    recorder.setPreviewDisplay(holder.getSurface());
    if (recorder != null) 
        try 
            recorder.prepare();
         catch (IllegalStateException e) 
            Log.e("IllegalStateException", e.toString());
         catch (IOException e) 
            Log.e("IOException", e.toString());
        
    


public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height) 


public void surfaceDestroyed(SurfaceHolder holder) 


public void setOutputFile(String filename)

    outputFile = filename;
    recorder.setOutputFile(filename);


public void startRecording()

    recorder.start();


public void stopRecording()

    recorder.stop();
    recorder.release();


【问题讨论】:

看看 - ***.com/questions/10186503/camera-app-not-working/… 我希望 [this][1] 对您有所帮助 [1]:***.com/questions/1817742/… 如果可以,请检查这个。 ***.com/questions/3956746/… 【参考方案1】:

使用这个简单的代码在android中录制视频非常简单

首先在一个按钮上单击简单的启动一个Intent

Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) 
    startActivityForResult(takeVideoIntent, CAMERA_REQUEST_CODE_VEDIO);

然后在onActivityResult方法中

Uri videoUri = data.getData();
path = Utils.getRealPathFromURI(videoUri, this);
manageVideo(path); //Do whatever you want with your video

最后为清单添加权限

<uses-feature
    android:name="android.hardware.camera"
    android:required="true" />

希望它能帮助其他正在寻求帮助的人:)

谢谢

【讨论】:

实用程序未定义。它需要哪个库。 它不是库,只是我创建的用于从 URI 获取路径的类。 getRealPathFromURI ? ***.com/questions/26195731/…【参考方案2】:
Uri contentUri="You record video uri";

try 
                                        Date date= new Date();
                                        android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", date);
                                        String Video_DIRECTORY = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + getString(R.string.app_name) + "/video/";
                                        File storeDirectory = new File(Video_DIRECTORY);

                                        try 
                                            if (storeDirectory.exists() == false) 
                                                storeDirectory.mkdirs();
                                            


                                         catch (Exception e) 
                                            e.printStackTrace();

                                        
                                        File storeDirectory12 = new File(storeDirectory,date+".mp4");
                                        InputStream inputStream = getContentResolver().openInputStream(contentUri);
                                        FileOutputStream fileOutputStream = new FileOutputStream(storeDirectory12);
                                        copyStream(inputStream, fileOutputStream);
                                        fileOutputStream.close();
                                        inputStream.close();
                                     catch (FileNotFoundException e) 
                                        Log.e("Exception", "" + e);
                                     catch (IOException e) 
                                        Log.e("Exception", "" + e);
                                    

【讨论】:

你在copyStream(inputStream, fileOutputStream)这个方法中做了什么【参考方案3】:
    // Put this code in ,on Button click or in onCreate to Capture the Video 


  Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    videoUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri);
    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
    startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);

  ////////////////////////////////


private static Uri getOutputMediaFileUri(int type)
    return Uri.fromFile(getOutputMediaFile(type));


private static File getOutputMediaFile(int type)
    // Check that the SDCard is mounted
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory() +"/YourDirectoryName");
    // Create the storage directory(MyCameraVideo) if it does not exist
    if (! mediaStorageDir.exists())

        if (! mediaStorageDir.mkdirs())

            Log.d("MyCameraVideo", "Failed to create directory MyCameraVideo.");
            return null;
        
    

    // Create a media file name
    // For unique file name appending current timeStamp with file name
    java.util.Date date= new java.util.Date();
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date.getTime());

    File mediaFile;
    if(type == MEDIA_TYPE_VIDEO) 

        // For unique video file name appending current timeStamp with file name
        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                "VID_"+ timeStamp + ".mp4");

     else 
        return null;
    

    return mediaFile;

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) 
    // After camera screen this code will execute
    if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE ) 

        if (resultCode == RESULT_OK) 
            videoUri = data.getData();

            // Video captured and saved to fileUri specified in the Intent
          //  Toast.makeText(getActivity(), "Video saved to: " +data.getData(), Toast.LENGTH_LONG).show();

         else if (resultCode == RESULT_CANCELED) 

            // User cancelled the video capture
            Toast.makeText(getActivity(), "User cancelled the video capture.", Toast.LENGTH_LONG).show();

         else 
           // Video capture failed, advise user
            Toast.makeText(getActivity(), "Video capture failed.", Toast.LENGTH_LONG).show();
        
    

【讨论】:

以上是关于在 Android 中录制、保存和播放视频的主要内容,如果未能解决你的问题,请参考以下文章

在 Android 中使用 GPU 进行视频录制和播放

Android:同时录制视频和播放 mp3?

尽管以纵向视图录制,但使用 mediaRecorder 和表面视图录制的 Android 视频无法在横向视图中播放

以字节格式录制和播放视频

我无法在 swift 2.3 中播放保存在目录路径和 AVPlayer 中的视频

安卓多媒体(视频录制播放音效播放)