audio-capture.jd revision 99b70f3f5d051261229d1792c169a374fc23326b
1page.title=Audio Capture
2parent.title=Multimedia and Camera 
3parent.link=index.html
4@jd:body
5
6    <div id="qv-wrapper">
7    <div id="qv">
8
9<h2>In this document</h2>
10<ol>
11<li><a href="#audiocapture">Performing Audio Capture</a>
12   <ol>
13      <li><a href='#example'>Code Example</a></li>
14   </ol>
15</li>
16</ol>
17
18<h2>Key classes</h2>
19<ol>
20<li>{@link android.media.MediaRecorder}</li>
21</ol>
22
23<h2>See also</h2>
24<ol>
25  <li><a href="{@docRoot}guide/appendix/media-formats.html">Android Supported Media Formats</a></li>
26  <li><a href="{@docRoot}guide/topics/data/data-storage.html">Data Storage</a></li>
27  <li><a href="{@docRoot}guide/topics/media/mediaplayer.html">MediaPlayer</a>
28</ol>
29
30</div>
31</div>
32
33<p>The Android multimedia framework includes support for capturing and encoding a variety of common
34audio formats, so that you can easily integrate audio into your applications. You can record audio
35using the {@link android.media.MediaRecorder} APIs if supported by the device hardware.</p>
36
37<p>This document shows you how to write an application that captures audio from a device
38microphone, save the audio and play it back.</p>
39
40<p class="note"><strong>Note:</strong> The Android Emulator does not have the ability to capture
41audio, but actual devices are likely to provide these capabilities.</p>
42
43<h2 id="audiocapture">Performing Audio Capture</h2>
44
45<p>Audio capture from the device is a bit more complicated than audio and video playback, but still
46fairly simple:</p>
47<ol>
48  <li>Create a new instance of {@link android.media.MediaRecorder android.media.MediaRecorder}.</li>
49  <li>Set the audio source using
50        {@link android.media.MediaRecorder#setAudioSource MediaRecorder.setAudioSource()}. You will
51probably want to use
52  <code>MediaRecorder.AudioSource.MIC</code>.</li>
53  <li>Set output file format using
54        {@link android.media.MediaRecorder#setOutputFormat MediaRecorder.setOutputFormat()}.
55  </li>
56  <li>Set output file name using
57        {@link android.media.MediaRecorder#setOutputFile MediaRecorder.setOutputFile()}.
58  </li>
59  <li>Set the audio encoder using
60        {@link android.media.MediaRecorder#setAudioEncoder MediaRecorder.setAudioEncoder()}.
61  </li>
62  <li>Call {@link android.media.MediaRecorder#prepare MediaRecorder.prepare()}
63   on the MediaRecorder instance.</li>
64  <li>To start audio capture, call
65  {@link android.media.MediaRecorder#start MediaRecorder.start()}. </li>
66  <li>To stop audio capture, call {@link android.media.MediaRecorder#stop MediaRecorder.stop()}.
67  <li>When you are done with the MediaRecorder instance, call
68{@link android.media.MediaRecorder#release MediaRecorder.release()} on it. Calling
69{@link android.media.MediaRecorder#release MediaRecorder.release()} is always recommended to
70free the resource immediately.</li>
71</ol>
72
73<h3 id="example">Example: Record audio and play the recorded audio</h3>
74<p>The example class below illustrates how to set up, start and stop audio capture, and to play the
75recorded audio file.</p>
76<pre>
77/*
78 * The application needs to have the permission to write to external storage
79 * if the output file is written to the external storage, and also the
80 * permission to record audio. These permissions must be set in the
81 * application's AndroidManifest.xml file, with something like:
82 *
83 * &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt;
84 * &lt;uses-permission android:name="android.permission.RECORD_AUDIO" /&gt;
85 *
86 */
87package com.android.audiorecordtest;
88
89import android.app.Activity;
90import android.widget.LinearLayout;
91import android.os.Bundle;
92import android.os.Environment;
93import android.view.ViewGroup;
94import android.widget.Button;
95import android.view.View;
96import android.view.View.OnClickListener;
97import android.content.Context;
98import android.util.Log;
99import android.media.MediaRecorder;
100import android.media.MediaPlayer;
101
102import java.io.IOException;
103
104
105public class AudioRecordTest extends Activity
106{
107    private static final String LOG_TAG = "AudioRecordTest";
108    private static String mFileName = null;
109
110    private RecordButton mRecordButton = null;
111    private MediaRecorder mRecorder = null;
112
113    private PlayButton   mPlayButton = null;
114    private MediaPlayer   mPlayer = null;
115
116    private void onRecord(boolean start) {
117        if (start) {
118            startRecording();
119        } else {
120            stopRecording();
121        }
122    }
123
124    private void onPlay(boolean start) {
125        if (start) {
126            startPlaying();
127        } else {
128            stopPlaying();
129        }
130    }
131
132    private void startPlaying() {
133        mPlayer = new MediaPlayer();
134        try {
135            mPlayer.setDataSource(mFileName);
136            mPlayer.prepare();
137            mPlayer.start();
138        } catch (IOException e) {
139            Log.e(LOG_TAG, "prepare() failed");
140        }
141    }
142
143    private void stopPlaying() {
144        mPlayer.release();
145        mPlayer = null;
146    }
147
148    private void startRecording() {
149        mRecorder = new MediaRecorder();
150        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
151        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
152        mRecorder.setOutputFile(mFileName);
153        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
154
155        try {
156            mRecorder.prepare();
157        } catch (IOException e) {
158            Log.e(LOG_TAG, "prepare() failed");
159        }
160
161        mRecorder.start();
162    }
163
164    private void stopRecording() {
165        mRecorder.stop();
166        mRecorder.release();
167        mRecorder = null;
168    }
169
170    class RecordButton extends Button {
171        boolean mStartRecording = true;
172
173        OnClickListener clicker = new OnClickListener() {
174            public void onClick(View v) {
175                onRecord(mStartRecording);
176                if (mStartRecording) {
177                    setText("Stop recording");
178                } else {
179                    setText("Start recording");
180                }
181                mStartRecording = !mStartRecording;
182            }
183        };
184
185        public RecordButton(Context ctx) {
186            super(ctx);
187            setText("Start recording");
188            setOnClickListener(clicker);
189        }
190    }
191
192    class PlayButton extends Button {
193        boolean mStartPlaying = true;
194
195        OnClickListener clicker = new OnClickListener() {
196            public void onClick(View v) {
197                onPlay(mStartPlaying);
198                if (mStartPlaying) {
199                    setText("Stop playing");
200                } else {
201                    setText("Start playing");
202                }
203                mStartPlaying = !mStartPlaying;
204            }
205        };
206
207        public PlayButton(Context ctx) {
208            super(ctx);
209            setText("Start playing");
210            setOnClickListener(clicker);
211        }
212    }
213
214    public AudioRecordTest() {
215        mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
216        mFileName += "/audiorecordtest.3gp";
217    }
218
219    &#64;Override
220    public void onCreate(Bundle icicle) {
221        super.onCreate(icicle);
222
223        LinearLayout ll = new LinearLayout(this);
224        mRecordButton = new RecordButton(this);
225        ll.addView(mRecordButton,
226            new LinearLayout.LayoutParams(
227                ViewGroup.LayoutParams.WRAP_CONTENT,
228                ViewGroup.LayoutParams.WRAP_CONTENT,
229                0));
230        mPlayButton = new PlayButton(this);
231        ll.addView(mPlayButton,
232            new LinearLayout.LayoutParams(
233                ViewGroup.LayoutParams.WRAP_CONTENT,
234                ViewGroup.LayoutParams.WRAP_CONTENT,
235                0));
236        setContentView(ll);
237    }
238
239    &#64;Override
240    public void onPause() {
241        super.onPause();
242        if (mRecorder != null) {
243            mRecorder.release();
244            mRecorder = null;
245        }
246
247        if (mPlayer != null) {
248            mPlayer.release();
249            mPlayer = null;
250        }
251    }
252}
253</pre>