Вы находитесь на странице: 1из 13

7/5/2015

News

AndroidAudioCaptureExample|ExamplesJavaCodeGeeks
KnowledgeBase

ANDROID

JobBoard

CORE JAVA

About

DESKTOP JAVA

ENTERPRISE JAVA

Search...

JAVA BASICS

HomeAndroidcoremediaMediaRecorderAndroidAudioCaptureExample

ABOUT KATERINA ZAMANI


KaterinahasgraduatedfromtheDepartmentofInformaticsandTelecommunicationsinNationalandKapodistrianUniversityofAthens
(NKUA)andsheattendsMSccoursesinAdvancedInformationSystemsatthesamedepartment.Currently,hermainacademic
interestsfocusonwebapplications,mobiledevelopment,softwareengineering,databasesandtelecommunications.

Android Audio Capture Example


Postedby:KaterinaZamani inMediaRecorder January3rd,2014

Androiddevicesareequippedwithhardwareinputdevicessuchasmicrophone,
cameraetc,fromwhichwecancaptureaudioorvideoinourapplications.Themost
commonclassthatisusedis
MediaRecorder

,whichrecordsaudioandvideo.
Inthisexample,wearegoingtocaptureaudiofromthedevicesmicrophone,storeit
tothedeviceandthenplayitbackand/orstopplayingit.

Forthistutorial,wewillusethefollowingtoolsinaWindows64bitplatform:
1. JDK1.7

NEWSLETTER

2. Eclipse4.2Juno
3. AndroidSDK4.4

1.CreateaNewAndroidApplicationProject
OpenEclipseIDEandgotoFileNewProjectAndroidApplicationProject.
Specifythenameoftheapplication,theprojectandthepackage.Also,set10APIorlargerastheminimumRequiredSDK,inordertosupport
theclasseswearegoingtouse.ThenpressNextbutton.

104082insidersarealreadyenjoying
weeklyupdatesandcomplimentary
whitepapers!

Jointhemnowtogainexclusive
accesstothelatestnewsintheJavaworld
aswellasinsightsaboutAndroid,Scala,
Groovyandotherrelatedtechnologies.

Emailaddress:
Youremailaddress
Signup

JOIN US

http://examples.javacodegeeks.com/android/core/media/mediarecorder/androidaudiocaptureexample/

1/13

7/5/2015

AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

With 1,240,600
uniquevisitorsandover
500 authorsweare
placedamongthetopJa
relatedsitesaround.
Constantlybeingonthe
lookoutforpartnerswe
encourageyoutojoinu
SoIfyouhaveablogw
uniqueandinterestingcontentthenyoushould
checkoutourJCGpartnersprogram.Youcana
beaguestwriterforJavaCodeGeeksandho
yourwritingskills!

Inthenextwindow,theCreateActivityoptionshouldbechecked.Thenewcreatedactivitywillbethemainactivityofyourproject.Thenclick
Next.

CAREER OPPORTUNITIES
Sr.SoftwareEngineer
CEIVABurbank,CA

JavaDeveloper
InnerWorkingsChicago,IL

JavaportalaccessingsqlDB
Houston,TX

FederalJavaWebDeveloper,Analyst...
InConfigureLauncherIconwindowyoushouldchoosetheiconyouwanttohaveinyourapp.Wewillusethedefaulticonofandroid,soclick
Next.

AccentureArlington,VA

SoftwareEngineerJava
GoDaddyScottsdale,AZ

TechnologyControllersTechnology...
GoldmanSachsJerseyCity,NJ

SoftwareEngineer(Java)
TrustwaveGreenwoodVillage,CO

ITAnalyst/ProgrammerJob
MayoClinicRochester,MN

JavaApplicationDeveloper
UniversityofCalifornia...Irvine,CA

JavaDeveloper/EngineerCo
WellsFargoNewYork,NY

12345678910Next
What:
title,keywords

Where:
city,state,orzip

FindJobs

http://examples.javacodegeeks.com/android/core/media/mediarecorder/androidaudiocaptureexample/

2/13

7/5/2015

AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

jobsby

SelecttheBlankActivityoptionandpressNext.

YouhavetospecifyanameforthenewActivityandanameforthelayoutdescriptionofyourapp.The.xmlfileforthelayoutwillautomatically
becreatedinthe
res/layout

folder.Finally,pressFinish.

http://examples.javacodegeeks.com/android/core/media/mediarecorder/androidaudiocaptureexample/

3/13

7/5/2015

AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

Youcanseethefinalstructureofthecreatedprojectintheimagebelow.

2.CreatethelayoutoftheMainActivity
Inthisapplication,wewanttostartandstoprecording,aswellasstartandstopplayingtherecordingsound.Forthisreasonwearegoingto
addfourdifferent
Buttons

inthelayout,whereeachoneenablestheappropriatefunctionality.Also,a
TextView

willbeusedtoshowusthecurrentsituation.

http://examples.javacodegeeks.com/android/core/media/mediarecorder/androidaudiocaptureexample/

4/13

7/5/2015

AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

Open
res/layout/activity_main.xml

gotothexmltabandpastethefollowing.
activity_main.xml:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70

<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="RecordingPoint:"
android:textAppearance="?android:attr/textAppearanceMedium"/>

<ImageView
android:id="@+id/micImage"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_below="@+id/text1"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:src="@android:drawable/presence_audio_online"/>
MasterJBossWildFlywithaFREEPackteBook!

<LinearLayoutandroid:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_below="@+id/micImage"
android:id="@+id/linear1"
android:orientation="horizontal">

<Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="start"/>

<Button
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:enabled="false"
android:text="stop"/>

</LinearLayout>

<LinearLayoutandroid:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_below="@+id/linear1"
android:id="@+id/linear2"
android:orientation="horizontal">

<Button
android:id="@+id/play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:enabled="false"
android:text="play"/>

<Button
android:id="@+id/stopPlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:enabled="false"
android:layout_marginLeft="10dp"
android:text="stopplaying"/>
</LinearLayout>

</RelativeLayout>

Noticethatweaddedan
ImageView

whereitscontentisapictureofaudiorecording,thatAndroidprovideusthroughthedrawable.

3.CodetheMainActivity
Foraudiorecord,weshouldcreateaninstanceof

MediaRecorder

classandsetsomeinformationaboutthesourceandtheoutputfile.Weuse
MediaRecorder.AudioSource.MIC

inordertosetthemicrophoneofthedeviceastheaudiosource.Inaddition,wehavetosettheformatandthenameoftheoutputfile,as

http://examples.javacodegeeks.com/android/core/media/mediarecorder/androidaudiocaptureexample/

5/13

7/5/2015

AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

wellastheaudioencoderfortheoutputfileinordertocontainanaudiotrack.Noticethatinourexample,wealsosetthepaththattheoutput
filewillbelocated.
Beforestartingtherecordingisveryimportanttopreparecapturingandencodingdata.Forthisreason,
prepare()

and
start()

methodsarecalled.Itisimportanttomentionthat
prepare()

methodmustbecalledbefore
start()

method,butafterthesettingofsource,formatandencodinginformation.Incontrast,tostopsoundrecording
stop()

methodshouldbecalled.Afterthat,iftheinstanceof
MediaRecorder

isnotusedanymore,itisrecommendedtofreetheresource,bycalling
release()

method.Ifyounoticeinthecodebelow,appropriate
Exceptions

arecalledforthespecificmethods.
Inourexample,wewanttoplaybackthesoundwejustrecorded,sowecreateaninstanceof
MediaPlayer

class.Afterspecifyingthesourcefilethatwewanttouse,
prepare()

and
start()

methodsarecalledinordertostartplayingtheaudiotrack.Respectively,
stop()

and
release()

methodsarecalledtostoptheplaybackandtofreethe
MediaPlayer

objectresources.
Open
src/com.javacodegeeks.android.audiocapturetest/MaainActivity.java

fileandpastethecodebelow.
MainActivity.java:
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019

packagecom.javacodegeeks.android.audiocapturetest;

importjava.io.IOException;
importandroid.media.MediaPlayer;
importandroid.media.MediaRecorder;
importandroid.os.Bundle;
importandroid.os.Environment;
importandroid.app.Activity;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
importandroid.widget.TextView;
importandroid.widget.Toast;

publicclassMainActivityextendsActivity{

privateMediaRecordermyRecorder;
privateMediaPlayermyPlayer;
privateStringoutputFile=null;

http://examples.javacodegeeks.com/android/core/media/mediarecorder/androidaudiocaptureexample/

6/13

7/5/2015
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123

AndroidAudioCaptureExample|ExamplesJavaCodeGeeks
privateButtonstartBtn;
privateButtonstopBtn;
privateButtonplayBtn;
privateButtonstopPlayBtn;
privateTextViewtext;

@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

text=(TextView)findViewById(R.id.text1);
//storeittosdcard
outputFile=Environment.getExternalStorageDirectory().
getAbsolutePath()+"/javacodegeeksRecording.3gpp";

myRecorder=newMediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setOutputFile(outputFile);

startBtn=(Button)findViewById(R.id.start);
startBtn.setOnClickListener(newOnClickListener(){

@Override
publicvoidonClick(Viewv){
//TODOAutogeneratedmethodstub
start(v);
}
});

stopBtn=(Button)findViewById(R.id.stop);
stopBtn.setOnClickListener(newOnClickListener(){

@Override
publicvoidonClick(Viewv){
//TODOAutogeneratedmethodstub
stop(v);
}
});

playBtn=(Button)findViewById(R.id.play);
playBtn.setOnClickListener(newOnClickListener(){

@Override
publicvoidonClick(Viewv){
//TODOAutogeneratedmethodstub
play(v);
}
});

stopPlayBtn=(Button)findViewById(R.id.stopPlay);
stopPlayBtn.setOnClickListener(newOnClickListener(){

@Override
publicvoidonClick(Viewv){
//TODOAutogeneratedmethodstub
stopPlay(v);
}
});
}

publicvoidstart(Viewview){
try{
myRecorder.prepare();
myRecorder.start();
}catch(IllegalStateExceptione){
//start:itiscalledbeforeprepare()
//prepare:itiscalledafterstart()orbeforesetOutputFormat()
e.printStackTrace();
}catch(IOExceptione){
//prepare()fails
e.printStackTrace();
}

text.setText("RecordingPoint:Recording");
startBtn.setEnabled(false);
stopBtn.setEnabled(true);

Toast.makeText(getApplicationContext(),"Startrecording...",
Toast.LENGTH_SHORT).show();
}

publicvoidstop(Viewview){
try{
myRecorder.stop();
myRecorder.release();
myRecorder=null;

stopBtn.setEnabled(false);
playBtn.setEnabled(true);
text.setText("RecordingPoint:Stoprecording");

Toast.makeText(getApplicationContext(),"Stoprecording...",
Toast.LENGTH_SHORT).show();
}catch(IllegalStateExceptione){
//itiscalledbeforestart()
e.printStackTrace();
}catch(RuntimeExceptione){
//novalidaudio/videodatahasbeenreceived
e.printStackTrace();
}
}

http://examples.javacodegeeks.com/android/core/media/mediarecorder/androidaudiocaptureexample/

7/13

7/5/2015

AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163

publicvoidplay(Viewview){
try{
myPlayer=newMediaPlayer();
myPlayer.setDataSource(outputFile);
myPlayer.prepare();
myPlayer.start();

playBtn.setEnabled(false);
stopPlayBtn.setEnabled(true);
text.setText("RecordingPoint:Playing");

Toast.makeText(getApplicationContext(),"Startplaytherecording...",
Toast.LENGTH_SHORT).show();
}catch(Exceptione){
//TODOAutogeneratedcatchblock
e.printStackTrace();
}
}

publicvoidstopPlay(Viewview){
try{
if(myPlayer!=null){
myPlayer.stop();
myPlayer.release();
myPlayer=null;
playBtn.setEnabled(true);
stopPlayBtn.setEnabled(false);
text.setText("RecordingPoint:Stopplaying");

Toast.makeText(getApplicationContext(),"Stopplayingtherecording...",
Toast.LENGTH_SHORT).show();
}
}catch(Exceptione){
//TODOAutogeneratedcatchblock
e.printStackTrace();
}
}

4.Setthepermissions
Wehavetodeclarethepermissionsinthe
AndroidManifest.xml

fileofourproject.
WRITE_EXTERNAL_STORAGE

istowritetheoutputfileintotheexternalstorageofourdevice(sdcard).
RECORD_AUDIO

isnecessaryfor
MediaRecorder

classtocaptureaudio.
Open
AndroidManifest.xml

fileandpastethefollowingcode.
AndroidManifest.xml:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

<?xmlversion="1.0"encoding="utf8"?>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.javacodegeeks.android.audiocapturetest"
android:versionCode="1"
android:versionName="1.0">

<usessdk
android:minSdkVersion="10"
android:targetSdkVersion="19"/>

<usespermissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<usespermissionandroid:name="android.permission.RECORD_AUDIO"/>

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name="com.javacodegeeks.android.audiocapturetest.MainActivity"
android:label="@string/app_name">
<intentfilter>
<actionandroid:name="android.intent.action.MAIN"/>

<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intentfilter>
</activity>
</application>

http://examples.javacodegeeks.com/android/core/media/mediarecorder/androidaudiocaptureexample/

8/13

7/5/2015

AndroidAudioCaptureExample|ExamplesJavaCodeGeeks
29
30 </manifest>

5.Runtheapplication
Inthisexample,wecantusetheandroidemulatortorunourapplication,becauseishasnttheabilitytocaptureaudio.Forthisreasonwe
havetoconnectEclipsewithourAndroiddeviceandruntheapplicationthroughit.
So,connectyourAndroiddevicewithyourpcthroughUSB.DontforgettoenableUSBdebuggingoption,byfollowingSettingsApplications
Developmentpath.
ThengotoEclipse,rightclickonourprojectRunasRunConfigurations.
Inthepopupwindowchoosethecurrentproject,gotothe
Target

tabandchooseAlwaysprompttopickdeviceoption.ThenclickNext.

FinallychoosetherunningAndroiddeviceandpressOK,asshowninthenextpicture.

TheappwillbeloadedinyourAndroiddevice,asyoucanseeintheimagebelow.

http://examples.javacodegeeks.com/android/core/media/mediarecorder/androidaudiocaptureexample/

9/13

7/5/2015

AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

Letspressstartbuttoninordertostartaudiorecording.Asyoucanseeinthepicturebelow,a
Toast

appearsandthe
TextView

issettoRecording.

Nowclickstopbutton.Theaudiotrackwillautomaticallybestoredintoyourexternalcard.Noticethatstopbuttonisnotclickableanymore.

http://examples.javacodegeeks.com/android/core/media/mediarecorder/androidaudiocaptureexample/

10/13

7/5/2015

AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

Ifyouwanttolistentotheaudioyoujustrecorded,pressplaybutton.The
TextView

willchangeagainanda
Toast

messagewillbeenabled.

Finally,pressstopplayingbuttonbeforetheaudiotrackends.Thismove,willstoptheaudioandwillenableplaybuttonagain,inorderto
listentoitagain.

http://examples.javacodegeeks.com/android/core/media/mediarecorder/androidaudiocaptureexample/

11/13

7/5/2015

AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

DownloadEclipseProject
ThiswasanexampleofAudioCaptureinAndroid.DownloadtheEclipseProjectofthisexample:AudioCaptureTest.zip

Taggedwith:

MEDIAPLAYER

DoyouwanttoknowhowtodevelopyourskillsettobecomeaJava
Rockstar?
SubscribetoournewslettertostartRockingrightnow!
TogetyoustartedwegiveyouourbestsellingeBooksforFREE!
1.JPAMiniBook
2.JVMTroubleshootingGuide
3.JUnitTutorialforUnitTesting
4.JavaAnnotationsTutorial
5.JavaInterviewQuestions
6.SpringInterviewQuestions
7.AndroidUIDesign
andmanymore....

Emailaddress:
Youremailaddress
Signup

http://examples.javacodegeeks.com/android/core/media/mediarecorder/androidaudiocaptureexample/

12/13

7/5/2015

KNOWLEDGE BASE

AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

HALL OF FAME

Academy

AndroidAlertDialogExample

Library

AndroidOnClickListenerExample

News

HowtoconvertCharactertoStringanda
StringtoCharacterArrayinJava

Resources
Tutorials
Whitepapers

THE CODE GEEKS NETWORK


.NETCodeGeeks
JavaCodeGeeks
WebCodeGeeks

JavaInheritanceexample
JavawritetoFileExample
java.io.FileNotFoundExceptionHowto
solveFileNotFoundException

ABOUT JAVA CODE GEEKS


JCGs(JavaCodeGeeks)isanindependentonlinecommunityfocusedoncreatingthe
ultimateJavatoJavadevelopersresourcecentertargetedatthetechnicalarchitect,
technicalteamlead(seniordeveloper),projectmanagerandjuniordevelopersalike.
JCGsservetheJava,SOA,AgileandTelecomcommunitieswithdailynewswrittenby
domainexperts,articles,tutorials,reviews,announcements,codesnippetsandopen
sourceprojects.

DISCLAIMER

AlltrademarksandregisteredtrademarksappearingonExamplesJavaCodeGeeksare
thepropertyoftheirrespectiveowners.Javaisatrademarkorregisteredtrademarkof
OracleCorporationintheUnitedStatesandothercountries.ExamplesJavaCodeGeeks
isnotconnectedtoOracleCorporationandisnotsponsoredbyOracleCorporation.

java.lang.arrayindexoutofboundsexception
HowtohandleArrayIndexOutOf
BoundsException
java.lang.NoClassDefFoundErrorHowto
solveNoClassDefFoundError
JSONExampleWithJersey+Jackson
SpringJdbcTemplateExample

ExamplesJavaCodeGeeksandallcontentcopyright20102015,ExelixisMediaP.C.|TermsofUse|PrivacyPolicy|Contact

http://examples.javacodegeeks.com/android/core/media/mediarecorder/androidaudiocaptureexample/

13/13

Вам также может понравиться