android audio capture example _ examples java code geeks

13
Home » Android » core » media » MediaRecorder » Android Audio Capture Example ABOUT KATERINA ZAMANI Katerina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she attends MSc courses in Advanced Information Systems at the same department. Currently, her main academic interests focus on web applications, mobile development, software engineering, databases and telecommunications. Android Audio Capture Example Posted by: Katerina Zamani in MediaRecorder January 3rd, 2014 Android devices are equipped with hardware input devices such as microphone, camera etc, from which we can capture audio or video in our applications. The most common class that is used is MediaRecorder , which records audio and video. In this example, we are going to capture audio from the device’s microphone, store it to the device and then play it back and/or stop playing it. For this tutorial, we will use the following tools in a Windows 64bit platform: 1. JDK 1.7 2. Eclipse 4.2 Juno 3. Android SDK 4.4 1. Create a New Android Application Project Open Eclipse IDE and go to File New Project Android Application Project. Specify the name of the application, the project and the package. Also, set 10 API or larger as the minimum Required SDK, in order to support the classes we are going to use. Then press Next button. NEWSLETTER 104082 insiders are already en weekly updates and complimentary whitepapers! Join them now to gain ex access to the latest news in the J as well as insights about Android, Sc Groovy and other related technologi Email address: Your email address Sign up JOIN US ANDROID CORE JAVA DESKTOP JAVA ENTERPRISE JAVA JAVA BASICS Search... News Knowledge Base Job Board About

Upload: neluehuri

Post on 01-Sep-2015

242 views

Category:

Documents


1 download

DESCRIPTION

Android

TRANSCRIPT

  • 7/5/2015 AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

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

    HomeAndroidcoremediaMediaRecorderAndroidAudioCaptureExample

    ABOUT KATERINA ZAMANIKaterinahasgraduatedfromtheDepartmentofInformaticsandTelecommunicationsinNationalandKapodistrianUniversityofAthens(NKUA)andsheattendsMSccoursesinAdvancedInformationSystemsatthesamedepartment.Currently,hermainacademicinterestsfocusonwebapplications,mobiledevelopment,softwareengineering,databasesandtelecommunications.

    Android Audio Capture Example Postedby:KaterinaZamani inMediaRecorder January3rd,2014

    Androiddevicesareequippedwithhardwareinputdevicessuchasmicrophone,cameraetc,fromwhichwecancaptureaudioorvideoinourapplications.ThemostcommonclassthatisusedisMediaRecorder

    ,whichrecordsaudioandvideo.

    Inthisexample,wearegoingtocaptureaudiofromthedevicesmicrophone,storeittothedeviceandthenplayitbackand/orstopplayingit.

    Forthistutorial,wewillusethefollowingtoolsinaWindows64bitplatform:

    1. JDK1.7

    2. Eclipse4.2Juno

    3. AndroidSDK4.4

    1.CreateaNewAndroidApplicationProjectOpenEclipseIDEandgotoFileNewProjectAndroidApplicationProject.

    Specifythenameoftheapplication,theprojectandthepackage.Also,set10APIorlargerastheminimumRequiredSDK,inordertosupporttheclasseswearegoingtouse.ThenpressNextbutton.

    NEWSLETTER

    104082insidersarealreadyenjoyingweeklyupdatesandcomplimentarywhitepapers!JointhemnowtogainexclusiveaccesstothelatestnewsintheJavaworld,aswellasinsightsaboutAndroid,Scala,Groovyandotherrelatedtechnologies.

    Emailaddress:

    Youremailaddress

    Signup

    JOIN US

    ANDROID CORE JAVA DESKTOP JAVA ENTERPRISE JAVA JAVA BASICS

    Search... News KnowledgeBase JobBoard About

  • 7/5/2015 AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

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

    Inthenextwindow,theCreateActivityoptionshouldbechecked.Thenewcreatedactivitywillbethemainactivityofyourproject.ThenclickNext.

    InConfigureLauncherIconwindowyoushouldchoosetheiconyouwanttohaveinyourapp.Wewillusethedefaulticonofandroid,soclickNext.

    With 1,240,600uniquevisitorsandover500 authorsweareplacedamongthetopJavarelatedsitesaround.Constantlybeingonthelookoutforpartnersweencourageyoutojoinus.SoIfyouhaveablogwith

    uniqueandinterestingcontentthenyoushouldcheckoutourJCGpartnersprogram.YoucanalsobeaguestwriterforJavaCodeGeeksandhoneyourwritingskills!

    CAREER OPPORTUNITIES

    What:

    title,keywords

    Where:

    city,state,orzip

    FindJobs

    Sr.SoftwareEngineerCEIVABurbank,CA

    JavaDeveloperInnerWorkingsChicago,IL

    JavaportalaccessingsqlDBHouston,TX

    FederalJavaWebDeveloper,Analyst...AccentureArlington,VA

    SoftwareEngineerJavaGoDaddyScottsdale,AZ

    TechnologyControllersTechnology...GoldmanSachsJerseyCity,NJ

    SoftwareEngineer(Java)TrustwaveGreenwoodVillage,CO

    ITAnalyst/ProgrammerJobMayoClinicRochester,MN

    JavaApplicationDeveloperUniversityofCalifornia...Irvine,CA

    JavaDeveloper/EngineerCoWellsFargoNewYork,NY12345678910Next

  • 7/5/2015 AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

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

    SelecttheBlankActivityoptionandpressNext.

    YouhavetospecifyanameforthenewActivityandanameforthelayoutdescriptionofyourapp.The.xmlfileforthelayoutwillautomaticallybecreatedintheres/layout

    folder.Finally,pressFinish.

    jobsby

  • 7/5/2015 AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

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

    Youcanseethefinalstructureofthecreatedprojectintheimagebelow.

    2.CreatethelayoutoftheMainActivityInthisapplication,wewanttostartandstoprecording,aswellasstartandstopplayingtherecordingsound.ForthisreasonwearegoingtoaddfourdifferentButtons

    inthelayout,whereeachoneenablestheappropriatefunctionality.Also,aTextView

    willbeusedtoshowusthecurrentsituation.

  • 7/5/2015 AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

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

    Openres/layout/activity_main.xml

    gotothexmltabandpastethefollowing.

    activity_main.xml:

    NoticethatweaddedanImageView

    whereitscontentisapictureofaudiorecording,thatAndroidprovideusthroughthedrawable.

    3.CodetheMainActivityForaudiorecord,weshouldcreateaninstanceofMediaRecorder

    classandsetsomeinformationaboutthesourceandtheoutputfile.WeuseMediaRecorder.AudioSource.MIC

    inordertosetthemicrophoneofthedeviceastheaudiosource.Inaddition,wehavetosettheformatandthenameoftheoutputfile,as

    01 06 07 14 15 23 24 30 31 36 37 44 45 46 47 53 54 60 61 68 69 70

    MasterJBossWildFlywithaFREEPackteBook!

  • 7/5/2015 AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

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

    wellastheaudioencoderfortheoutputfileinordertocontainanaudiotrack.Noticethatinourexample,wealsosetthepaththattheoutputfilewillbelocated.

    Beforestartingtherecordingisveryimportanttopreparecapturingandencodingdata.Forthisreason,prepare()

    andstart()

    methodsarecalled.Itisimportanttomentionthatprepare()

    methodmustbecalledbeforestart()

    method,butafterthesettingofsource,formatandencodinginformation.Incontrast,tostopsoundrecordingstop()

    methodshouldbecalled.Afterthat,iftheinstanceofMediaRecorder

    isnotusedanymore,itisrecommendedtofreetheresource,bycallingrelease()

    method.Ifyounoticeinthecodebelow,appropriateExceptions

    arecalledforthespecificmethods.

    Inourexample,wewanttoplaybackthesoundwejustrecorded,sowecreateaninstanceofMediaPlayer

    class.Afterspecifyingthesourcefilethatwewanttouse,prepare()

    andstart()

    methodsarecalledinordertostartplayingtheaudiotrack.Respectively,stop()

    andrelease()

    methodsarecalledtostoptheplaybackandtofreetheMediaPlayer

    objectresources.

    Opensrc/com.javacodegeeks.android.audiocapturetest/MaainActivity.java

    fileandpastethecodebelow.

    MainActivity.java:

    001 packagecom.javacodegeeks.android.audiocapturetest;002 003 importjava.io.IOException;004 importandroid.media.MediaPlayer;005 importandroid.media.MediaRecorder;006 importandroid.os.Bundle;007 importandroid.os.Environment;008 importandroid.app.Activity;009 importandroid.view.View;010 importandroid.view.View.OnClickListener;011 importandroid.widget.Button;012 importandroid.widget.TextView;013 importandroid.widget.Toast;014 015 publicclassMainActivityextendsActivity{016 017 privateMediaRecordermyRecorder;018 privateMediaPlayermyPlayer;019 privateStringoutputFile=null;

  • 7/5/2015 AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

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

    020 privateButtonstartBtn;021 privateButtonstopBtn;022 privateButtonplayBtn;023 privateButtonstopPlayBtn;024 privateTextViewtext;025 026 @Override027 protectedvoidonCreate(BundlesavedInstanceState){028 super.onCreate(savedInstanceState);029 setContentView(R.layout.activity_main);030 031 text=(TextView)findViewById(R.id.text1);032 //storeittosdcard033 outputFile=Environment.getExternalStorageDirectory().034 getAbsolutePath()+"/javacodegeeksRecording.3gpp";035 036 myRecorder=newMediaRecorder();037 myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);038 myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);039 myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);040 myRecorder.setOutputFile(outputFile);041 042 startBtn=(Button)findViewById(R.id.start);043 startBtn.setOnClickListener(newOnClickListener(){044 045 @Override046 publicvoidonClick(Viewv){047 //TODOAutogeneratedmethodstub048 start(v);049 }050 });051 052 stopBtn=(Button)findViewById(R.id.stop);053 stopBtn.setOnClickListener(newOnClickListener(){054 055 @Override056 publicvoidonClick(Viewv){057 //TODOAutogeneratedmethodstub058 stop(v);059 }060 });061 062 playBtn=(Button)findViewById(R.id.play);063 playBtn.setOnClickListener(newOnClickListener(){064 065 @Override066 publicvoidonClick(Viewv){067 //TODOAutogeneratedmethodstub068 play(v);069 }070 });071 072 stopPlayBtn=(Button)findViewById(R.id.stopPlay);073 stopPlayBtn.setOnClickListener(newOnClickListener(){074 075 @Override076 publicvoidonClick(Viewv){077 //TODOAutogeneratedmethodstub078 stopPlay(v);079 }080 });081 }082 083 publicvoidstart(Viewview){084 try{085 myRecorder.prepare();086 myRecorder.start();087 }catch(IllegalStateExceptione){088 //start:itiscalledbeforeprepare()089 //prepare:itiscalledafterstart()orbeforesetOutputFormat()090 e.printStackTrace();091 }catch(IOExceptione){092 //prepare()fails093 e.printStackTrace();094 }095 096 text.setText("RecordingPoint:Recording");097 startBtn.setEnabled(false);098 stopBtn.setEnabled(true);099 100 Toast.makeText(getApplicationContext(),"Startrecording...",101 Toast.LENGTH_SHORT).show();102 }103 104 publicvoidstop(Viewview){105 try{106 myRecorder.stop();107 myRecorder.release();108 myRecorder=null;109 110 stopBtn.setEnabled(false);111 playBtn.setEnabled(true);112 text.setText("RecordingPoint:Stoprecording");113 114 Toast.makeText(getApplicationContext(),"Stoprecording...",115 Toast.LENGTH_SHORT).show();116 }catch(IllegalStateExceptione){117 //itiscalledbeforestart()118 e.printStackTrace();119 }catch(RuntimeExceptione){120 //novalidaudio/videodatahasbeenreceived121 e.printStackTrace();122 }123 }

  • 7/5/2015 AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

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

    4.SetthepermissionsWehavetodeclarethepermissionsintheAndroidManifest.xml

    fileofourproject.WRITE_EXTERNAL_STORAGE

    istowritetheoutputfileintotheexternalstorageofourdevice(sdcard).RECORD_AUDIO

    isnecessaryforMediaRecorder

    classtocaptureaudio.

    OpenAndroidManifest.xml

    fileandpastethefollowingcode.

    AndroidManifest.xml:

    124 125 publicvoidplay(Viewview){126 try{127 myPlayer=newMediaPlayer();128 myPlayer.setDataSource(outputFile);129 myPlayer.prepare();130 myPlayer.start();131 132 playBtn.setEnabled(false);133 stopPlayBtn.setEnabled(true);134 text.setText("RecordingPoint:Playing");135 136 Toast.makeText(getApplicationContext(),"Startplaytherecording...",137 Toast.LENGTH_SHORT).show();138 }catch(Exceptione){139 //TODOAutogeneratedcatchblock140 e.printStackTrace();141 }142 }143 144 publicvoidstopPlay(Viewview){145 try{146 if(myPlayer!=null){147 myPlayer.stop();148 myPlayer.release();149 myPlayer=null;150 playBtn.setEnabled(true);151 stopPlayBtn.setEnabled(false);152 text.setText("RecordingPoint:Stopplaying");153 154 Toast.makeText(getApplicationContext(),"Stopplayingtherecording...",155 Toast.LENGTH_SHORT).show();156 }157 }catch(Exceptione){158 //TODOAutogeneratedcatchblock159 e.printStackTrace();160 }161 }162 163 }

    01 02 06 07 10 11 12 13 14 19 22 23 24 25 26 27 28

  • 7/5/2015 AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

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

    5.RuntheapplicationInthisexample,wecantusetheandroidemulatortorunourapplication,becauseishasnttheabilitytocaptureaudio.ForthisreasonwehavetoconnectEclipsewithourAndroiddeviceandruntheapplicationthroughit.

    So,connectyourAndroiddevicewithyourpcthroughUSB.DontforgettoenableUSBdebuggingoption,byfollowingSettingsApplicationsDevelopmentpath.

    ThengotoEclipse,rightclickonourprojectRunasRunConfigurations.

    Inthepopupwindowchoosethecurrentproject,gototheTarget

    tabandchooseAlwaysprompttopickdeviceoption.ThenclickNext.

    FinallychoosetherunningAndroiddeviceandpressOK,asshowninthenextpicture.

    TheappwillbeloadedinyourAndroiddevice,asyoucanseeintheimagebelow.

    29 30

  • 7/5/2015 AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

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

    Letspressstartbuttoninordertostartaudiorecording.Asyoucanseeinthepicturebelow,aToast

    appearsandtheTextView

    issettoRecording.

    Nowclickstopbutton.Theaudiotrackwillautomaticallybestoredintoyourexternalcard.Noticethatstopbuttonisnotclickableanymore.

  • 7/5/2015 AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

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

    Ifyouwanttolistentotheaudioyoujustrecorded,pressplaybutton.TheTextView

    willchangeagainandaToast

    messagewillbeenabled.

    Finally,pressstopplayingbuttonbeforetheaudiotrackends.Thismove,willstoptheaudioandwillenableplaybuttonagain,inordertolistentoitagain.

  • 7/5/2015 AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

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

    DownloadEclipseProjectThiswasanexampleofAudioCaptureinAndroid.DownloadtheEclipseProjectofthisexample:AudioCaptureTest.zip

    Taggedwith: MEDIAPLAYER

    DoyouwanttoknowhowtodevelopyourskillsettobecomeaJavaRockstar?

    SubscribetoournewslettertostartRockingrightnow!TogetyoustartedwegiveyouourbestsellingeBooksforFREE!1.JPAMiniBook2.JVMTroubleshootingGuide3.JUnitTutorialforUnitTesting4.JavaAnnotationsTutorial5.JavaInterviewQuestions6.SpringInterviewQuestions7.AndroidUIDesign

    andmanymore....

    Emailaddress:

    Youremailaddress

    Signup

  • 7/5/2015 AndroidAudioCaptureExample|ExamplesJavaCodeGeeks

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

    KNOWLEDGE BASE

    Academy

    Library

    News

    Resources

    Tutorials

    Whitepapers

    THE CODE GEEKS NETWORK

    .NETCodeGeeks

    JavaCodeGeeks

    WebCodeGeeks

    HALL OF FAME

    AndroidAlertDialogExample

    AndroidOnClickListenerExample

    HowtoconvertCharactertoStringandaStringtoCharacterArrayinJava

    JavaInheritanceexample

    JavawritetoFileExample

    java.io.FileNotFoundExceptionHowtosolveFileNotFoundException

    java.lang.arrayindexoutofboundsexceptionHowtohandleArrayIndexOutOfBoundsException

    java.lang.NoClassDefFoundErrorHowtosolveNoClassDefFoundError

    JSONExampleWithJersey+Jackson

    SpringJdbcTemplateExample

    ABOUT JAVA CODE GEEKS

    JCGs(JavaCodeGeeks)isanindependentonlinecommunityfocusedoncreatingtheultimateJavatoJavadevelopersresourcecentertargetedatthetechnicalarchitect,technicalteamlead(seniordeveloper),projectmanagerandjuniordevelopersalike.JCGsservetheJava,SOA,AgileandTelecomcommunitieswithdailynewswrittenbydomainexperts,articles,tutorials,reviews,announcements,codesnippetsandopensourceprojects.

    DISCLAIMER

    AlltrademarksandregisteredtrademarksappearingonExamplesJavaCodeGeeksarethepropertyoftheirrespectiveowners.JavaisatrademarkorregisteredtrademarkofOracleCorporationintheUnitedStatesandothercountries.ExamplesJavaCodeGeeksisnotconnectedtoOracleCorporationandisnotsponsoredbyOracleCorporation.

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