0% found this document useful (0 votes)
38 views13 pages

Android Audio Capture Example - Examples Java Code Geeks

Android

Uploaded by

nelu_ehuri
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views13 pages

Android Audio Capture Example - Examples Java Code Geeks

Android

Uploaded by

nelu_ehuri
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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)[Link],hermainacademic
interestsfocusonwebapplications,mobiledevelopment,softwareengineering,databasesandtelecommunications.

Android Audio Capture Example


Postedby:KaterinaZamani inMediaRecorder January3rd,2014

Androiddevicesareequippedwithhardwareinputdevicessuchasmicrophone,
cameraetc,[Link]
commonclassthatisusedis
MediaRecorder

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

Forthistutorial,wewillusethefollowingtoolsinaWindows64bitplatform:
1. JDK1.7

NEWSLETTER

2. Eclipse4.2Juno
3. AndroidSDK4.4

[Link]
OpenEclipseIDEandgotoFileNewProjectAndroidApplicationProject.
Specifythenameoftheapplication,[Link],set10APIorlargerastheminimumRequiredSDK,inordertosupport
[Link].

104082insidersarealreadyenjoying
weeklyupdatesandcomplimentary
whitepapers!

Jointhemnowtogainexclusive
accesstothelatestnewsintheJavaworld
aswellasinsightsaboutAndroid,Scala,
Groovyandotherrelatedtechnologies.

Emailaddress:
Youremailaddress
Signup

JOIN US

[Link]

1/13

7/5/2015

AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

With 1,240,600
uniquevisitorsandover
500 authorsweare
placedamongthetopJa
relatedsitesaround.
Constantlybeingonthe
lookoutforpartnerswe
encourageyoutojoinu
SoIfyouhaveablogw
uniqueandinterestingcontentthenyoushould
[Link]
beaguestwriterforJavaCodeGeeksandho
yourwritingskills!

Inthenextwindow,[Link]
Next.

CAREER OPPORTUNITIES
[Link]
CEIVABurbank,CA

JavaDeveloper
InnerWorkingsChicago,IL

JavaportalaccessingsqlDB
Houston,TX

FederalJavaWebDeveloper,Analyst...
[Link],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

[Link]

2/13

7/5/2015

AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

jobsby

SelecttheBlankActivityoptionandpressNext.

[Link]
becreatedinthe
res/layout

[Link],pressFinish.

[Link]

3/13

7/5/2015

AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

Youcanseethefinalstructureofthecreatedprojectintheimagebelow.

[Link]
Inthisapplication,wewanttostartandstoprecording,[Link]
addfourdifferent
Buttons

inthelayout,[Link],a
TextView

willbeusedtoshowusthecurrentsituation.

[Link]

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="[Link]
xmlns:tools="[Link]
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.

[Link]
Foraudiorecord,weshouldcreateaninstanceof

MediaRecorder

[Link]
[Link]

[Link],wehavetosettheformatandthenameoftheoutputfile,as

[Link]

5/13

7/5/2015

AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

[Link],wealsosetthepaththattheoutput
filewillbelocated.
[Link],
prepare()

and
start()

[Link]
prepare()

methodmustbecalledbefore
start()

method,butafterthesettingofsource,[Link],tostopsoundrecording
stop()

[Link],iftheinstanceof
MediaRecorder

isnotusedanymore,itisrecommendedtofreetheresource,bycalling
release()

[Link],appropriate
Exceptions

arecalledforthespecificmethods.
Inourexample,wewanttoplaybackthesoundwejustrecorded,sowecreateaninstanceof
MediaPlayer

[Link],
prepare()

and
start()

[Link],
stop()

and
release()

methodsarecalledtostoptheplaybackandtofreethe
MediaPlayer

objectresources.
Open
src/[Link]/[Link]

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

[Link];

[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];

publicclassMainActivityextendsActivity{

privateMediaRecordermyRecorder;
privateMediaPlayermyPlayer;
privateStringoutputFile=null;

[Link]

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){
[Link](savedInstanceState);
setContentView([Link].activity_main);

text=(TextView)findViewById([Link].text1);
//storeittosdcard
outputFile=[Link]().
getAbsolutePath()+"/javacodegeeksRecording.3gpp";

myRecorder=newMediaRecorder();
[Link]([Link]);
[Link]([Link].THREE_GPP);
[Link]([Link].AMR_NB);
[Link](outputFile);

startBtn=(Button)findViewById([Link]);
[Link](newOnClickListener(){

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

stopBtn=(Button)findViewById([Link]);
[Link](newOnClickListener(){

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

playBtn=(Button)findViewById([Link]);
[Link](newOnClickListener(){

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

stopPlayBtn=(Button)findViewById([Link]);
[Link](newOnClickListener(){

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

publicvoidstart(Viewview){
try{
[Link]();
[Link]();
}catch(IllegalStateExceptione){
//start:itiscalledbeforeprepare()
//prepare:itiscalledafterstart()orbeforesetOutputFormat()
[Link]();
}catch(IOExceptione){
//prepare()fails
[Link]();
}

[Link]("RecordingPoint:Recording");
[Link](false);
[Link](true);

[Link](getApplicationContext(),"Startrecording...",
Toast.LENGTH_SHORT).show();
}

publicvoidstop(Viewview){
try{
[Link]();
[Link]();
myRecorder=null;

[Link](false);
[Link](true);
[Link]("RecordingPoint:Stoprecording");

[Link](getApplicationContext(),"Stoprecording...",
Toast.LENGTH_SHORT).show();
}catch(IllegalStateExceptione){
//itiscalledbeforestart()
[Link]();
}catch(RuntimeExceptione){
//novalidaudio/videodatahasbeenreceived
[Link]();
}
}

[Link]

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();
[Link](outputFile);
[Link]();
[Link]();

[Link](false);
[Link](true);
[Link]("RecordingPoint:Playing");

[Link](getApplicationContext(),"Startplaytherecording...",
Toast.LENGTH_SHORT).show();
}catch(Exceptione){
//TODOAutogeneratedcatchblock
[Link]();
}
}

publicvoidstopPlay(Viewview){
try{
if(myPlayer!=null){
[Link]();
[Link]();
myPlayer=null;
[Link](true);
[Link](false);
[Link]("RecordingPoint:Stopplaying");

[Link](getApplicationContext(),"Stopplayingtherecording...",
Toast.LENGTH_SHORT).show();
}
}catch(Exceptione){
//TODOAutogeneratedcatchblock
[Link]();
}
}

[Link]
Wehavetodeclarethepermissionsinthe
[Link]

fileofourproject.
WRITE_EXTERNAL_STORAGE

istowritetheoutputfileintotheexternalstorageofourdevice(sdcard).
RECORD_AUDIO

isnecessaryfor
MediaRecorder

classtocaptureaudio.
Open
[Link]

fileandpastethefollowingcode.
[Link]:
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="[Link]
package="[Link]"
android:versionCode="1"
android:versionName="1.0">

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

<usespermissionandroid:name="[Link].WRITE_EXTERNAL_STORAGE"/>
<usespermissionandroid:name="[Link].RECORD_AUDIO"/>

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name="[Link]"
android:label="@string/app_name">
<intentfilter>
<actionandroid:name="[Link]"/>

<categoryandroid:name="[Link]"/>
</intentfilter>
</activity>
</application>

[Link]

8/13

7/5/2015

AndroidAudioCaptureExample|ExamplesJavaCodeGeeks
29
30 </manifest>

[Link]
Inthisexample,wecantusetheandroidemulatortorunourapplication,[Link]
havetoconnectEclipsewithourAndroiddeviceandruntheapplicationthroughit.
So,[Link],byfollowingSettingsApplications
Developmentpath.
ThengotoEclipse,rightclickonourprojectRunasRunConfigurations.
Inthepopupwindowchoosethecurrentproject,gotothe
Target

[Link].

FinallychoosetherunningAndroiddeviceandpressOK,asshowninthenextpicture.

TheappwillbeloadedinyourAndroiddevice,asyoucanseeintheimagebelow.

[Link]

9/13

7/5/2015

AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

[Link],a
Toast

appearsandthe
TextView

issettoRecording.

[Link].

[Link]

10/13

7/5/2015

AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

Ifyouwanttolistentotheaudioyoujustrecorded,[Link]
TextView

willchangeagainanda
Toast

messagewillbeenabled.

Finally,[Link],willstoptheaudioandwillenableplaybuttonagain,inorderto
listentoitagain.

[Link]

11/13

7/5/2015

AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

DownloadEclipseProject
[Link]:[Link]

Taggedwith:

MEDIAPLAYER

DoyouwanttoknowhowtodevelopyourskillsettobecomeaJava
Rockstar?
SubscribetoournewslettertostartRockingrightnow!
TogetyoustartedwegiveyouourbestsellingeBooksforFREE!
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
andmanymore....

Emailaddress:
Youremailaddress
Signup

[Link]

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
[Link]
solveFileNotFoundException

ABOUT JAVA CODE GEEKS


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

DISCLAIMER

AlltrademarksandregisteredtrademarksappearingonExamplesJavaCodeGeeksare
[Link]
[Link]
isnotconnectedtoOracleCorporationandisnotsponsoredbyOracleCorporation.

[Link]
HowtohandleArrayIndexOutOf
BoundsException
[Link]
solveNoClassDefFoundError
JSONExampleWithJersey+Jackson
SpringJdbcTemplateExample

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

[Link]

13/13

You might also like