Android mediarecorder recording audio and video code snippets

Source: Internet
Author: User

Android mobile devices provide a lot of hardware for users to operate and many API interfaces for programmers to call. Java code calls C code to drive hardware devices, such a sophisticated set of implementation solutions.

Just like single-chip microcomputer control requires many parameters, Android calls a hardware device also requires a lot of parameters, also known as parameters, which can be used to control hardware, memory, or files in various ways.

1: Recording

The following is a simple Android recording code. For reference only:

private MediaRecorder mMediaRecorder;                    mMediaRecorder = new MediaRecorder();          mMediaRecorder              .setAudioSource(MediaRecorder.AudioSource.MIC);          mMediaRecorder              .setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);          mMediaRecorder              .setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);          mMediaRecorder.setOutputFile(myRecAudioFile              .getAbsolutePath());          mMediaRecorder.prepare();          mMediaRecorder.start();

Several lines of code from new instance to prepare are set parameters. You can also set other parameters to view the differences. Prepare means that the recording device starts to prepare to capture the data of the input device and encode the data. This means that everything is ready, just wait for the first moment. For the specific code of prepare, see:

   /**     * Prepares the recorder to begin capturing and encoding data. This method     * must be called after setting up the desired audio and video sources,     * encoders, file format, etc., but before start().     *     * @throws IllegalStateException if it is called after     * start() or before setOutputFormat().     * @throws IOException if prepare fails otherwise.     */    public void prepare() throws IllegalStateException, IOException    {        if (mPath != null) {            FileOutputStream fos = new FileOutputStream(mPath);            try {                _setOutputFile(fos.getFD(), 0, 0);            } finally {                fos.close();            }        } else if (mFd != null) {            _setOutputFile(mFd, 0, 0);        } else {            throw new IOException("No valid output file");        }        _prepare();    }

It can be seen that a file is needed for output during prepare, otherwise it will be too late to detect problems such as file unavailability at the beginning of recording, so be prepared at this time. Then call the native method: setoutfile and prepare. For the function prototype, see:

    // native implementation    private native void _setOutputFile(FileDescriptor fd, long offset, long length)        throws IllegalStateException, IOException;    private native void _prepare() throws IllegalStateException, IOException;

After the recording is completed, stop the recording device and release the memory. If the recording device stops, the recording device still occupies the memory, which is equivalent to the ready state, that is, the status is unreasonable.

Mmediarecorder. Stop ();
Mmediarecorder. Release ();
Mmediarecorder = NULL;

The source code release is explained as follows:

    /**     * Releases resources associated with this MediaRecorder object.     * It is good practice to call this method when you're done     * using the MediaRecorder.     */    public native void release();

Use of mediarecorder native code is described as follows:

A common case of using MediaRecorder to record audio works as follows:MediaRecorder recorder = new MediaRecorder();  recorder.setAudioSource(MediaRecorder.AudioSource.MIC);  recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);  recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);  recorder.setOutputFile(PATH_NAME);  recorder.prepare();  recorder.start();   // Recording is now started  ...  recorder.stop();  recorder.reset();   // You can reuse the object by going back to setAudioSource() step  recorder.release(); // Now the object cannot be reused

2: Video Recording

The recorded video also adjusts the mediarecorder parameters. The Code is as follows:

To start recording a video, you need to provide the file path. to preview the video screen, you can provide the surface, so that you can record and watch it.

 MediaRecorder recorder = null;        File outFile = new File(OUTPUT_FILE);        if (outFile.exists()) {            outFile.delete();        }        try {            recorder = new MediaRecorder();            recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);            recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);            recorder.setVideoSize(480, 320);            recorder.setVideoFrameRate(15);            recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);            recorder.setPreviewDisplay(holder.getSurface());            recorder.setOutputFile(OUTPUT_FILE);            recorder.prepare();            recorder.start();        } catch (Exception e) {            e.printStackTrace();        }

The same is true for stopping a recorded video:

        if (recorder != null) {            recorder.stop();            recorder.release();        }

Do not forget to add the permission. However, if you forget to add the permission, you will be prompted for a lack of permission for the operation and easy to locate. You only need to remember the common permissions.

<uses-permission android:name="android.permission.CAMERA" /><uses-permission android:name="android.permission.RECORD_AUDIO" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.