"Android" 20.4 recording

Source: Internet
Author: User

Category: C #, Android, VS2015;

Date Created: 2016-03-13 I. INTRODUCTION

Use the Mediarecorder class provided with Android to record audio directly.

1. Permission Requirements

The following permissions are required to record audio and video:

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

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

2. Basic design Steps (1) initialization and recording

The basic design steps for recording audio are as follows:

(1) Create a Mediarecorder object.

(2) Call the Setaudiosource method to specify which hardware device is used to capture audio input (such as a microphone).

(3) Call the Setoutputformat method to specify the format of the recording output file.

(4) Call the Setaudioencoder method to set the audio encoding type.

(5) Call the Setoutputfile method to specify the output audio file.

(6) Call the Prepare method to initialize the recorder.

(7) Call the Start method to start recording.

The following code shows how to implement:

protected Mediarecorder Recorder;

void Recordaudio (String filePath)

{

try {

if (file.exists (FilePath)) {

File.delete (FilePath);

}

if (recorder = = null) {

Recorder = new Mediarecorder (); Initial state.

} else {

Recorder. Reset ();

Recorder. Setaudiosource (audiosource.mic);

Recorder. Setoutputformat (OUTPUTFORMAT.THREEGPP);

Recorder. Setaudioencoder (AUDIOENCODER.AMRNB);

Initialized state.

Recorder. Setoutputfile (FilePath);

Datasourceconfigured state.

Recorder. Prepare (); Prepared State

Recorder. Start (); Recording state.

}

} catch (Exception ex) {

Console.Out.WriteLine (ex. StackTrace);

}

} (2) Stop recording

Call the Stop method of Mediarecorder to stop recording:

Recorder. Stop (); (3) Clear the resources occupied by the recording

Once the Mediarecorder is stopped, the reset method is called to put it idle (idle state):

Recorder. Reset ();

When you no longer use an Mediarecorder instance, you must free the resources that it occupies:

Recorder. Release (); Ii. examples

The function of this example is to record audio from the microphone, and if the notebook has a microphone, it can be viewed directly from the simulator to see how it works. After recording, you can test the effect of the recording directly by clicking the play button.

This is also a simple example of not taking into account the phone-breaking situation during the recording process, nor considering other complex controls.

1. Operation

2. Design steps

(1) Androidmanifest.xml file

Add the following permissions to the file (you do not have to add them if you have one).

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

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

(2) Add Ch2004main.axml file

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"android:orientation= "vertical"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent">  <ButtonAndroid:id= "@+id/ch2004_btnrecstart"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Start Recording" />  <ButtonAndroid:id= "@+id/ch2004_btnrecstop"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Stop Recording" />  <ButtonAndroid:id= "@+id/ch2004_btnplaystart"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Play recording" />  <ButtonAndroid:id= "@+id/ch2004_btnplaystop"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Stop playing recording" />  <TextViewandroid:textappearance= "? Android:attr/textappearancemedium"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:id= "@+id/ch2004_textview1"android:gravity= "Center_horizontal"Android:layout_margintop= "30DP" /></LinearLayout>

(3) Add Ch2004MainActivity.cs file

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingAndroid.app;usingandroid.content;usingAndroid.os;usingAndroid.runtime;usingandroid.views;usingAndroid.widget;usingAndroid.media;namespacemydemos.srcdemos{[Activity (Label="ch2004mainactivity")] [Intentfilter (New[] {intent.actionmain}, Categories=New[] {intent.categorydefault, ch. Mydemoscategory})] Public classch2004mainactivity:activity {stringFilePath;        Mediarecorder Recorder;        MediaPlayer player;        Button Btnrecstart, Btnrecstop, Btnplaystart, btnplaystop;        TextView TextView1; protected Override voidOnCreate (Bundle savedinstancestate) {Base.            OnCreate (savedinstancestate);            Setcontentview (Resource.Layout.ch2004Main); //Specify the audio file path for the SD card recordingFilePath =string. Format ("{0}/{1}/myrecord.mp3", Android.OS.Environment.ExternalStorageDirectory.Path, Android.OS.Environment.Directory            Music); TextView1= findviewbyid<textview>(RESOURCE.ID.CH2004_TEXTVIEW1); Btnrecstart= findviewbyid<button>(Resource.Id.ch2004_btnRecStart); Btnrecstart.click+=Delegate{Textview1.text="Recording now ..."; Try{startrecorder (); }                Catch(Exception ex) {Console.Out.WriteLine (ex).                StackTrace);            }            }; Btnrecstop= findviewbyid<button>(Resource.Id.ch2004_btnRecStop); Btnrecstop.click+=Delegate{stoprecorder (); Textview1.text="The recording has been stopped. ";            }; Btnplaystart= findviewbyid<button>(Resource.Id.ch2004_btnPlayStart); Btnplaystart.click+=Delegate{Textview1.text="playing recording ..."; Try{player=NewMediaPlayer (); Player.                    Reset (); Player.                    Setdatasource (FilePath); Player.                    Prepare (); Player.                Start (); }                Catch(Exception ex) {Console.WriteLine (ex).                StackTrace);            }            }; Btnplaystop= findviewbyid<button>(Resource.Id.ch2004_btnPlayStop); Btnplaystop.click+=Delegate{player.                Stop (); Textview1.text="playback is stopped. ";        }; }        Private voidStartrecorder () {Try            {                if(System.IO.File.Exists (FilePath)) {System.IO.File.Delete (FilePath); }                if(Recorder = =NULL) {Recorder=NewMediarecorder ();//Initial state.                }                Else{Recorder.                Reset (); } recorder.  Setaudiosource (audiosource.mic); //recording sound from a microphoneRecorder.                Setoutputformat (OUTPUTFORMAT.MPEG4); Recorder.                Setaudioencoder (AUDIOENCODER.AMRNB); Recorder.                Setoutputfile (FilePath); Recorder.                Prepare (); Recorder.            Start (); }            Catch(Exception ex) {Console.Out.WriteLine (ex).            StackTrace); }        }        Private voidStoprecorder () {if(Recorder! =NULL) {Recorder.                Stop (); Recorder.                Release (); Recorder=NULL; }        }    }}

Observe the effect of running in the simulator, click the "Record" button to start recording, after recording, click "Play recording" to test the recording effect.

"Android" 20.4 recording

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.