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>

53 comments :

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

    ReplyDelete
  2. 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
  3. short[] lin = new short[1024];
    int num = 0;

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

    ReplyDelete
  4. 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
  5. This comment has been removed by the author.

    ReplyDelete
  6. How to add resource mp3 file to AudioTrack

    ReplyDelete
  7. hi frnds,

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

    can you send me code for this

    Thanks

    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. 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
  10. 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
  11. 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
  12. 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
  13. 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
  14. 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
  15. 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
  16. 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
  17. This was an nice and amazing and the given contents were very useful and the precision given here is good.

    Training

    ReplyDelete
  18. 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
  19. 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
  20. Guys I m getting an error ‘unfortunately your app has stopped ‘ plz help me

    ReplyDelete
  21. 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
  22. Thanks for the tutorial, it helps me lot, thanks for the code

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

    ReplyDelete
  24. 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
  25. 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
  26. Really it was an awesome article,very interesting to read.You have provided an nice article,Thanks for sharing.informatica training in bangalore

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

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

    ReplyDelete
  29. 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

  30. 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
  31. 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
  32. This comment has been removed by the author.

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

    ReplyDelete
  34. 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

  35. 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
  36. Hey guy's i have got something to share from my research work
    Coderefinery
    Tukui
    Lakedrops

    ReplyDelete