Android Audio Demo - AudioTrack , AudioRecord - (Echo Sample)

Simple echo application for how to use android AudioTrack and AudioRecord classes
Download Source
Step 1
    Create MainActivity class for audio record and play

package com.javaorigin.audio;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
 AudioManager am = null;
 AudioRecord record =null;
 AudioTrack track =null;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  setVolumeControlStream(AudioManager.MODE_IN_COMMUNICATION);
  init();
  (new Thread() {
   @Override
   public void run() {
    recordAndPlay();
   }
  }).start();
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

 private void init() {
  int min = AudioRecord.getMinBufferSize(8000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
  record = new AudioRecord(MediaRecorder.AudioSource.VOICE_COMMUNICATION, 8000, AudioFormat.CHANNEL_IN_MONO,
    AudioFormat.ENCODING_PCM_16BIT, min);

  int maxJitter = AudioTrack.getMinBufferSize(8000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
  track = new AudioTrack(AudioManager.MODE_IN_COMMUNICATION, 8000, AudioFormat.CHANNEL_OUT_MONO,
    AudioFormat.ENCODING_PCM_16BIT, maxJitter, AudioTrack.MODE_STREAM);
 }

 private void recordAndPlay() {
  short[] lin = new short[1024];
  int num = 0;
  am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
  am.setMode(AudioManager.MODE_IN_COMMUNICATION);
  record.startRecording();
  track.play();
  while (true) {
   num = record.read(lin, 0, 1024);
   track.write(lin, 0, num);
  }
 }
 
 boolean isSpeaker = false;

 public void modeChange(View view) {
  Button modeBtn=(Button) findViewById(R.id.modeBtn);
  if (isSpeaker == true) {   
   am.setSpeakerphoneOn(false);
   isSpeaker = false;
   modeBtn.setText("Call Mode");
  } else {   
   am.setSpeakerphoneOn(true);
   isSpeaker = true;
   modeBtn.setText("Speaker Mode");
  }
 }
    
 boolean isPlaying=true;
 public void play(View view){
  Button playBtn=(Button) findViewById(R.id.playBtn);
  if(isPlaying){
   record.stop();
   track.pause();
   isPlaying=false;
   playBtn.setText("Play");
  }else{
   record.startRecording();
   track.play();
   isPlaying=true;
   playBtn.setText("Pause");
  }
 }
 
}
Step 2
        Add Button for Play/Pause and Call mode/ Speaker mode
<RelativeLayout xmlns: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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >



    <Button
        android:id="@+id/modeBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="24dp"
        android:text="Call Mode" 
        android:onClick="modeChange"/>

    <Button
        android:id="@+id/playBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/modeBtn"
        android:layout_alignBottom="@+id/modeBtn"
        android:layout_marginLeft="30dp"
        android:layout_toRightOf="@+id/modeBtn"
        android:onClick="play"
        android:text="Pause" />

</RelativeLayout>

Step 3
    Add audio related permission to Android.xml
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"></uses-permission>
    <uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>

117 comments :

  1. Replies
    1. Great Article android based projects

      Java Training in Chennai

      Project Center in Chennai

      Java Training in Chennai

      projects for cse

      The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

      Delete
  2. pls upload screen shots of app as well with your source code, thnks for this code ..

    ReplyDelete
  3. Works Great.......

    But I want to give delay in replying the sound ....for that I have done maxJitter*19 . and it worked
    But I have increased the audiotrack frequency i.e.
    track = new AudioTrack(AudioManager.MODE_IN_COMMUNICATION, 9000, AudioFormat.CHANNEL_OUT_MONO,
    AudioFormat.ENCODING_PCM_16BIT, maxJitter, AudioTrack.MODE_STREAM);

    after giving 9000 frequency it gives me delay for sometimes only and after that it immediately replies to my voice which I really don't want ....

    Plz Help me in this...
    Thanks in advance

    ReplyDelete
  4. short[] lin = new short[1024];
    int num = 0;

    I wonder why lin.length() = 1024??
    how do you have this num?

    ReplyDelete
  5. int min = AudioRecord.getMinBufferSize(8000,
    AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT);
    record = new AudioRecord(MediaRecorder.AudioSource.VOICE_COMMUNICATION,
    8000, AudioFormat.CHANNEL_IN_STEREO,
    AudioFormat.ENCODING_PCM_16BIT, min);

    int maxJitter = AudioTrack.getMinBufferSize(8000,
    AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT);
    track = new AudioTrack(AudioManager.MODE_IN_COMMUNICATION, 8000,
    AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT,
    maxJitter, AudioTrack.MODE_STREAM);

    when i change AudioFormat.CHANNEL_OUT_MONO to AudioFormat.CHANNEL_OUT_STEREO, it can't work?!!
    Some one help me plz!!
    thanks

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. How to add resource mp3 file to AudioTrack

    ReplyDelete
  8. hi frnds,

    i want to record my incoming and out going calls in my phone

    can you send me code for this

    Thanks

    ReplyDelete
  9. hi frnds,

    i want to record my incoming and out going calls in my phone

    can you send me code for this

    Thanks

    ReplyDelete
  10. This was an nice and amazing and the given contents were very useful and the precision given here is good.
    java training in chennai

    java training in bangalore

    java online training

    java training in pune

    ReplyDelete
  11. Thanks a lot very much for the high quality and results-oriented help. I won’t think twice to endorse your blog post to anybody who wants and needs support about this area.python training in chennai

    python training in bangalore

    python online training

    python training in pune

    ReplyDelete
  12. Fantastic work! This is the type of information that should follow collective approximately the web. Embarrassment captivating position Google for not positioning this transmit higher! Enlarge taking place greater than and visit my web situate
    Data Science training in chennai
    Data science training in velachery
    Data science training in tambaram
    Data Science training in OMR
    Data Science training in anna nagar
    Data Science training in chennai
    Data science training in Bangalore
    Data Science training in marathahalli

    ReplyDelete
  13. After reading this web site I am very satisfied simply because this site is providing comprehensive knowledge for you to audience. Thank you to the perform as well as discuss anything incredibly important in my opinion. We loose time waiting for your next article writing in addition to I beg one to get back to pay a visit to our website in
    python training in rajajinagar
    Python training in btm
    Python training in usa

    ReplyDelete
  14. This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.. 
    DevOps online Training
    DevOps Training in USA

    ReplyDelete
  15. Hello! This is my first visit to your blog! We are a team of volunteers and starting a new initiative in a community in the same niche. Your blog provided us useful information to work on. You have done an outstanding job.

    AWS Online Training | Online AWS Certification Course - Gangboard
    AWS Training in Chennai | AWS Training Institute in Chennai Velachery, Tambaram, OMR
    AWS Training in Bangalore |Best AWS Training Institute in BTM ,Marathahalli

    ReplyDelete
  16. myTectra Placement Portal is a Web based portal brings Potentials Employers and myTectra Candidates on a common platform for placement assistance

    ReplyDelete
  17. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Blueprism training in Chennai

    Blueprism training in Bangalore

    ReplyDelete
  18. Does your blog have a contact page? I’m having problems locating it but, I’d like to shoot you an email. I’ve got some recommendations for your blog you might be interested in hearing.
    AWS Training in Chennai |Best Amazon Web Services Training in Chennai
    AWS Training in Rajaji Nagar | Amazon Web Services Training in Rajaji Nagar

    Best AWS Training Institute in BTM Layout Bangalore ,AWS Coursesin BTM

    ReplyDelete
  19. Amazon Web Services (AWS) is the most popular and most widely used Infrastructure as a Service (IaaS) cloud in the world.AWS has four core feature buckets—Compute, Storage & Content Delivery, Databases, and Networking. At a high level, you can control all of these with extensive administrative controls accessible via a secure Web client.For more information visit aws online
    training

    ReplyDelete
  20. Good job in presenting the correct content with the clear explanation. The content looks real with valid information. Good Work

    DevOps is currently a popular model currently organizations all over the world moving towards to it. Your post gave a clear idea about knowing the DevOps model and its importance.

    Good to learn about DevOps at this time.


    devops training in chennai | devops training in chennai with placement | devops training in chennai omr | devops training in velachery | devops training in chennai tambaram | devops institutes in chennai | devops certification in chennai

    ReplyDelete
  21. The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea.
    here by i also want to share this.
    data science online training
    python online training
    uipath online training
    data science with python online training
    rpa online training

    ReplyDelete
  22. I was recommended this web site by means of my cousin. I am now not certain whether this post is written through him as nobody else recognise such precise about my difficulty. You're amazing! Thank you!
    angularjs online training

    apache spark online training

    informatica mdm online training

    devops online training

    aws online training

    ReplyDelete
  23. Fantastic work! This is the type of information that should follow collective approximately the web. Embarrassment captivating position Google for not positioning this transmit higher! Enlarge taking place greater than and visit my web situate

    Microsoft Azure online training
    Selenium online training
    Java online training
    Java Script online training
    Share Point online training


    ReplyDelete
  24. This was an nice and amazing and the given contents were very useful and the precision given here is good.

    Training

    ReplyDelete
  25. Attend The Python training in bangalore From ExcelR. Practical Python training in bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python training in bangalore.
    python training in bangalore

    ReplyDelete
  26. hello guys... i get an error "uses or overrides a deprecated api"...i used API 23 to run this code...on executing i got an error "Your app isn't working " ...someone help me !!

    ReplyDelete
  27. Guys I m getting an error ‘unfortunately your app has stopped ‘ plz help me

    ReplyDelete
  28. I feel very grateful that I read this. It is very helpful and very informative and I Python training in pune really learned a lot from it.

    ReplyDelete
  29. I learned World's Trending Technology from certified experts for free of cost. I Got a job in decent Top MNC Company with handsome 14 LPA salary, I have learned the World's Trending Technology from Data science training in btm layout experts who know advanced concepts which can help to solve any type of Real-time issues in the field of Python. Really worth trying hkbk group of institutions

    ReplyDelete
  30. Thanks for the tutorial, it helps me lot, thanks for the code

    ReplyDelete
  31. Very interesting blog Thank you for sharing such a nice and interesting blog and really very helpful article.python training in bangalore

    ReplyDelete
  32. Its really helpful for the users of this site. I am also searching about these type of sites now a days. So your site really helps me for searching the new and great stuff.vmware training in bangalore

    ReplyDelete
  33. Very useful and information content has been shared out here, Thanks for sharing it.aws training in bangalore

    ReplyDelete
  34. I gathered a lot of information through this article.Every example is easy to undestandable and explaining the logic easily.mulesoft training in bangalore

    ReplyDelete
  35. These provided information was really so nice,thanks for giving that post and the more skills to develop after refer that post.salesforce developer training in bangalore

    ReplyDelete
  36. Linking is very useful thing.you have really helped lots of people who visit blog and provide them use full information.devops training in bangalore

    ReplyDelete
  37. Being new to the blogging world I feel like there is still so much to learn. Your tips helped to clarify a few things for me as well as giving.servicenow training in bangalore

    ReplyDelete
  38. Really it was an awesome article,very interesting to read.You have provided an nice article,Thanks for sharing.informatica training in bangalore

    ReplyDelete
  39. I know that it takes a lot of effort and hard work to write such an informative content like this.cloud computing training in bangalore

    ReplyDelete
  40. Really it was an awesome article,very interesting to read.You have provided an nice article,Thanks for sharing.devops Training in Bangalore

    ReplyDelete
  41. This comment has been removed by the author.

    ReplyDelete
  42. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    servicenow online training
    top servicenow online training
    best servicenow online training

    ReplyDelete

  43. Class College Education training Beauty teaching university academy lesson teacher master student spa manager skin care learn eyelash extensions tattoo spray

    daythammynet
    daythammynet
    daythammynet
    daythammynet
    daythammynet
    daythammynet
    daythammynet
    daythammynet
    daythammynet

    ReplyDelete
  44. Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing. sharepoint developer training.

    ReplyDelete
  45. Great blog !It is best institute.Top Training institute In Velachery
    http://trainingsinvelachery.in/bi-bw-training-in-velachery/
    http://trainingsinvelachery.in/solidworks-training-in-velachery/
    http://trainingsinvelachery.in/autocad-training-in-velachery/
    http://trainingsinvelachery.in/ansys-training-in-velachery/
    http://trainingsinvelachery.in/revit-architecture-training-in-velachery/
    http://trainingsinvelachery.in/primavera-training-in-velachery/

    ReplyDelete
  46. Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care
    http://chennaitraining.in/creo-training-in-chennai/
    http://chennaitraining.in/building-estimation-and-costing-training-in-chennai/
    http://chennaitraining.in/machine-learning-training-in-chennai/
    http://chennaitraining.in/data-science-training-in-chennai/
    http://chennaitraining.in/rpa-training-in-chennai/
    http://chennaitraining.in/blueprism-training-in-chennai/

    ReplyDelete
  47. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    http://onlinejobsupport.net/online-job-support-from-india/
    http://onlinejobsupport.net/job-support/java-online-job-support/
    http://onlinejobsupport.net/job-support/php-online-job-support/
    http://onlinejobsupport.net/job-support/selenium-online-job-support/
    http://onlinejobsupport.net/job-support/dotnet-online-job-support/
    http://onlinejobsupport.net/job-support/devops-online-job-support/
    http://onlinejobsupport.net/job-support/manual-testing-online-job-support/

    ReplyDelete
  48. This comment has been removed by the author.

    ReplyDelete
  49. Thanks for sharing such a great information..Its really nice and informative..
    azure online training

    ReplyDelete
  50. This is so elegant and logical and clearly explained. Brilliantly goes through what could be a complex process sharepoint training online and makes it obvious.

    ReplyDelete
  51. Effective blog with a lot of information. I just Shared you the link below for ACTE .They really provide good level of training and Placement,I just Had Microsoft Azure Classes in ACTE , Just Check This Link You can get it more information about the Microsoft Azure course.

    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete

  52. This is most informative and also this post most user friendly and super navigation to all posts. Thank you so much for giving this information to me. Informative training in Chennai.

    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  53. Writing, like great art requires much more than knowledge and education. A great writer is born as opposed to ""made"" and you are a great writer. This is excellent content and interesting information. Thank you.
    Best Data Science training in Mumbai

    Data Science training in Mumbai

    ReplyDelete
  54. Hey guy's i have got something to share from my research work
    Coderefinery
    Tukui
    Lakedrops

    ReplyDelete

  55. Firstly talking about the Blog it is providing the great information providing by you . Thanks for that .Hope More articles from you . Next i want to share some information about Salesforce training in Banglore .

    ReplyDelete
  56. Thank you for posting informative insights, I think we have got some more information to share with! Do check out Python Training In Chennai and let us know your thoughts. Let’s have great learning!

    ReplyDelete
  57. Thanks for posting the best information and the blog is very helpful.python course in Bangalore

    ReplyDelete
  58. Learn Big Data for making your career towards a sky-high with Infycle Technologies. Infycle Technologies is the best Big Data training institute, providing courses for the Big Data certification in Chennai in 200% hands-on practical training with professional trainers in the domain. Apart from the training, the placement interviews will be arranged for the students, so that they can set their career without any struggle. Of all that, 100% placement assurance will be given here. To have the best career, call 7502633633 to Infycle Technologies and grab a free demo to know more.Big Data Training in Chennai

    ReplyDelete
  59. Reach to the best Data Science Training institute in Chennai for skyrocketing your career, Infycle Technologies. It is the best Software Training & Placement institutes in and around Chennai. that also gives the best placement training for personality tests, interview preparation, and mock interviews for leveling up the candidate's grades to a professional level.

    ReplyDelete
  60. Chennai's best software training institute, Infycle Technologies, offers the No.1 Oracle DBA training in Chennai for tech professionals & students along with other courses such as Python, Big Data, Selenium, Java, Hadoop, iOS, and Android development with 100% hands-on training. Once the completion of training, the students will be sent for placement interviews in the core MNC's. Call 7502633633 to get more info and a free demo.Top Oracle DBA Training in Chennai | Infycle Technologies

    ReplyDelete
  61. Infycle Technologies, the best software training institute in Chennai offers the leading Data Science course in Chennai for tech professionals, freshers, and students at the best offers. In addition to the Data Science course, other in-demand courses such as Python, Cyber Security, Selenium, Oracle, Java, Power BI, Digital Marketing also will be trained with 100% practical classes. After the completion of training, the trainees will be sent for placement interviews in the top MNC's. Call 7504633633 to get more info and a free demo.

    ReplyDelete
  62. Infycle Technologies, the top software training institute and placement center in Chennai offers the Best Digital Marketing Course in Chennai | Infycle Technologies for freshers, students, and tech professionals at the best offers. In addition to Digital Marketing, other in-demand courses such as DevOps, Data Science, Python, Selenium, Big Data, Java, Power BI, Oracle will also be trained with 100% practical classes. After the completion of training, the trainees will be sent for placement interviews in the top MNC's. Call 7504633633 to get more info and a free demo.

    ReplyDelete
  63. Amazing Article! I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
    Data science course in pune

    ReplyDelete
  64. Learn Amazon Web Services for excellent job opportunities from Infycle Technologies, the Excellent AWS Training in Chennai. Infycle Technologies gives the most trustworthy AWS course in Chennai, with full hands-on practical training from professional trainers in the field. Along with that, the placement interviews will be arranged for the candidates, so that, they can meet the job interviews without missing them. To transform your career to the next level, call 7502633633 to Infycle Technologies and grab a free demo to know more

    ReplyDelete
  65. Infycle Technologies, the best software training institute in Chennai. Perfect place to learn Big Data Hadoop Training in Chennai for experienced, and Tech professionals. And we also put up other courses like Data Science, Manual and Automation Testing, DevOps, Medical Coding, Oracle, Java, Data Science, AWS, Python, etc., at the end of the course period the pupil will be able to crack jobs on top MNC’s. for more details call 7504633633.

    ReplyDelete
  66. DataDukan pride itself in delivering a full spectrum of IT solutions and services, helping you make the shift to the next level of digital experiences.
    Best IT Solutions Companies in Mumbai specialize in transformative strategic consulting and offer domain-centric solutions in
    the areas of data management, business intelligence, visualization, predictive & prescriptive analytics and artificial intelligence. It offers services to companies from
    varied sectors including financial services, cable and telecommunications, retail, fashion, media & entertainment and more. The company believes in offering top-quality services
    in a completely transparent and ethical way.

    ReplyDelete
  67. Chemistry is our forte. We provide chemicals ranging from fine chemcials for early R&D application to large scale industrial production. Glycidol (556-52-5 ) manufacturer USA is a leading developer, manufacturer and exporter of API, intermediates of API, Fragrance intermediates, Specialty Chemicals & other Customized Products.
    Located in Asia's largest chemical industrial estate, Rampur, U.P., Agex Pharma begins its operations as a small scale unit in 1990 and in a span of three decades in market has emerged as a leading player
    which believes in quality. Today with an inventory of 500+ products, 200+ clients globally Agex Pharma has placed itself in one of the most sought after companies in the nation for Fine and Rare Specialty
    chemicals.Our business is based on a simple philosophy: to provide our customers with high quality fine chemicals at reasonable prices and with fast turn-around schedules.

    ReplyDelete
  68. This post is so interactive and informative.keep update more information...
    Salesforce Training in Velachery
    Salesforce Training in Chennai

    ReplyDelete
  69. If you are searching for an Ethical Hackers Academy then you should be join Cyber Crime Awareness Society. Cyber Crime Awareness Society is one of the Best Hacking Course In Jaipur. Cyber Crime Awareness Society is IT Consulting Company managed by Ethical Hackers & IT professionals, working with Police Agencies and Cyber Crime Cell of Government in India. It is also backed by a team of Experts working with RAW, CBI, ATS, IB and Cyber Crime Cell with an aim to create India the safest place of internet in the World.

    ReplyDelete