Tuesday 30 April 2013

CharacterPickerDialog in Android


You can create custom character Picker, same way we can make custom keyboard using this concept. 


import android.app.Activity;
import android.os.Bundle;
import android.text.method.CharacterPickerDialog;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Toast;

public class CharacterPickerDialogActivity extends Activity
{    
      private CharacterPickerDialog cpd = null;
      String options="0123456789ABCDEFGHIJ";
     
      @Override
      public void onCreate(Bundle savedInstanceState)
      {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            Button button = (Button) this.findViewById(R.id.Button01);
            button.setOnClickListener(new View.OnClickListener()
            {
                  @Override
                  public void onClick(View v)
                  {
                        cpd.show();
                  }
            });          
            cpdnew CharacterPickerDialog(thisnew View(this),     null,options,false)
            {
                  public void onClick(View v)
                  {

                   Toast.makeText(getApplicationContext(),"onClick! " +  ((Button) v).getText().toString(),
                        Toast.LENGTH_SHORT).show();
                        dismiss();
                  }
                  public void onItemClick(AdapterView parent, View view, int position, longid)
                  {
                    String message = ("onItemClick! " + ((Button)       view).getText().toString())
                        + " position=" + position + " id=" + id;
                       
                        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
                        dismiss();
                  }
            };
      }
}

Audio Recorder in Android


The android.media.AudioRecord class manages the audio resources for Java applications to record audio from the audio input hardware of the platform.



record.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="HB-Record Audio" />

    <Button
        android:id="@+id/startrec"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Start Recording" />

    <Button
        android:id="@+id/stoprec"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Stop Recording" />

    <Button
        android:id="@+id/playback"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Play Back" />

</LinearLayout>


AndroidAudioRecordActivity:

public class AndroidAudioRecordActivity extends Activity
{

      Button startRecstopRecplayBack;
      Boolean recording;
     
      @Override
      public void onCreate(Bundle savedInstanceState)
      {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.record);
           
            startRec = (Button)findViewById(R.id.startrec);
            stopRec = (Button)findViewById(R.id.stoprec);
            playBack = (Button)findViewById(R.id.playback);

            startRec.setOnClickListener(startRecOnClickListener);
            stopRec.setOnClickListener(stopRecOnClickListener);
            playBack.setOnClickListener(playBackOnClickListener);

      }

      OnClickListener startRecOnClickListener   = new OnClickListener()
      {
            @Override
            public void onClick(View arg0)
            {
                  Thread recordThread = new Thread(new Runnable()
                  {
                        @Override
                        public void run()
                        {
                              recording = true;
                              startRecord();
                        }

                  });

                  recordThread.start();
            }};

            OnClickListener stopRecOnClickListener = new OnClickListener()
            {
                  @Override
                  public void onClick(View arg0)
                  {
                        recording = false;
                  }};

                  OnClickListener playBackOnClickListener   = new OnClickListener()
                  {

                        @Override
                        public void onClick(View v)
                        {
                              playRecord();
                        }

                  };

                  private void startRecord()
                  { 
                        File file = new File(Environment.getExternalStorageDirectory(),"test.pcm");

                        try
                        {
                              file.createNewFile();

                              OutputStream outputStream = new FileOutputStream(file);
                              BufferedOutputStream bufferedOutputStream = newBufferedOutputStream(outputStream);
                              DataOutputStream dataOutputStream = newDataOutputStream(bufferedOutputStream);

                              int minBufferSize = AudioRecord.getMinBufferSize(11025,
                                          AudioFormat.CHANNEL_CONFIGURATION_MONO,
                                          AudioFormat.ENCODING_PCM_16BIT);

                              short[] audioData = new short[minBufferSize];

                              AudioRecord audioRecord = newAudioRecord(MediaRecorder.AudioSource.MIC,
                                          11025,
                                          AudioFormat.CHANNEL_CONFIGURATION_MONO,
                                          AudioFormat.ENCODING_PCM_16BIT,
                                          minBufferSize);

                              audioRecord.startRecording();

                              while(recording)
                              {
                                    int numberOfShort = audioRecord.read(audioData, 0, minBufferSize);
                                    for(int i = 0; i < numberOfShort; i++)
                                    {
                                          dataOutputStream.writeShort(audioData[i]);
                                    }
                              }
                              audioRecord.stop();
                              dataOutputStream.close();

                        }
                        catch (IOException e)
                        {
                              e.printStackTrace();
                        }

                  }

                  void playRecord()
                  {
                        File file = new File(Environment.getExternalStorageDirectory(),"test.pcm");

                        int shortSizeInBytes = Short.SIZE/Byte.SIZE;

                        int bufferSizeInBytes = (int)(file.length()/shortSizeInBytes);
                        short[] audioData = new short[bufferSizeInBytes];

                        try {
                              InputStream inputStream = new FileInputStream(file);
                              BufferedInputStream bufferedInputStream = newBufferedInputStream(inputStream);
                              DataInputStream dataInputStream = newDataInputStream(bufferedInputStream);

                              int i = 0;
                              while(dataInputStream.available() > 0)
                              {
                                    audioData[i] = dataInputStream.readShort();
                                    i++;
                              }

                              dataInputStream.close();

                              AudioTrack audioTrack = new AudioTrack(
                                          AudioManager.STREAM_MUSIC,
                                          11025,
                                          AudioFormat.CHANNEL_CONFIGURATION_MONO,
                                          AudioFormat.ENCODING_PCM_16BIT,
                                          bufferSizeInBytes,
                                          AudioTrack.MODE_STREAM);

                              audioTrack.play();
                              audioTrack.write(audioData, 0, bufferSizeInBytes);


                        } catch (FileNotFoundException e)
                        {
                              e.printStackTrace();
                        } catch (IOException e)
                        {
                              e.printStackTrace();
                        }
                  } 
}

Permission:
  <uses-permission android:name="android.permission.RECORD_AUDIO" />
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Click here for more ref Link:

Monday 29 April 2013


Audio Player in android.

* Live Audio streaming:*

This example has been prepared to stream any audio file from specific URL, and when I have been created this example, I used Android 2.2.
In this sample, I have used one activity, is implemented four interfaces, again. These are:
1. OnClickListener : onClick() method is used, when one of the button has been pushed.
2. OnTouchListener : onTouch() method is used for seeking audio.
3. OnCompletionListener : To set enable of  the buttons, overriden onCompletion() method is just used.
4. OnBufferingUpdateListener : onBufferingUpdate() method is used to update secondary progress of the seekBar instance.


Main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@android:color/darker_gray">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        android:textColor="@android:color/black"/>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:gravity="center_horizontal"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btn_play"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:text="play" >
        </Button>

        <Button
            android:id="@+id/btn_pause"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:text="pause" >
        </Button>

        <Button
            android:id="@+id/btn_stop"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:text="stop" >
        </Button>
    </LinearLayout>

    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="3dp" >
    </SeekBar>

</LinearLayout>


 StreamAudioFromUrlSampleActivity:
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.SeekBar; 

public class StreamAudioFromUrlSampleActivity extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{
       private Button btn_play,
       btn_pause,
       btn_stop;
       private SeekBar seekBar;
       private MediaPlayer mediaPlayer;
       private int lengthOfAudio;
       private final String URL = "AudioUrl";


       private final Handler handler = new Handler();
       private final Runnable r = new Runnable()
       {     
              @Override
              public void run() {
                     updateSeekProgress();                                 
              }
       };

       @Override
       public void onCreate(Bundle savedInstanceState)
       {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
              initialize_Controls();
       }

       private void initialize_Controls()
       {
              btn_play = (Button)findViewById(R.id.btn_play);
              btn_play.setOnClickListener(this);
              btn_pause = (Button)findViewById(R.id.btn_pause);
              btn_pause.setOnClickListener(this);
              btn_pause.setEnabled(false);
              btn_stop = (Button)findViewById(R.id.btn_stop);
              btn_stop.setOnClickListener(this);
              btn_stop.setEnabled(false);

              seekBar = (SeekBar)findViewById(R.id.seekBar);
              seekBar.setOnTouchListener(this);

              mediaPlayer = new MediaPlayer();
              mediaPlayer.setOnBufferingUpdateListener(this);
              mediaPlayer.setOnCompletionListener(this);

       }

       @Override
       public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent)
       {
              seekBar.setSecondaryProgress(percent);
       }

       @Override
       public void onCompletion(MediaPlayer mp)
       {
              btn_play.setEnabled(true);
              btn_pause.setEnabled(false);
              btn_stop.setEnabled(false);
       }

       @Override
       public boolean onTouch(View v, MotionEvent event)
       {
              if (mediaPlayer.isPlaying())
              {
                     SeekBar tmpSeekBar = (SeekBar)v;
                     mediaPlayer.seekTo((lengthOfAudio / 100) * tmpSeekBar.getProgress() );
              }
              return false;
       }

       @Override
       public void onClick(View view)
       {

              try
              {                         
                     mediaPlayer.setDataSource(URL);
                     mediaPlayer.prepare();
                     lengthOfAudio = mediaPlayer.getDuration();                   
             
              }
              catch (Exception e)
              {
                     //Log.e("Error", e.getMessage());
              }

              switch (view.getId())
              {
              case R.id.btn_play:              
                     playAudio();
                     break;
              case R.id.btn_pause:
                     pauseAudio();
                     break;
              case R.id.btn_stop:
                     stopAudio();
                     break;
              default:
                     break;
              }

              updateSeekProgress();
       }

       private void updateSeekProgress()
       {
              if (mediaPlayer.isPlaying())
              {
                     seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / lengthOfAudio) * 100));
                     handler.postDelayed(r, 1000);
              }
       }

       private void stopAudio()
       {
              if(mediaPlayer!=null)
              {
                     mediaPlayer.stop();
              }
              btn_play.setEnabled(true);
              btn_pause.setEnabled(false);
              btn_stop.setEnabled(false);
              seekBar.setProgress(0);
       }

       private void pauseAudio()
       {
              if(mediaPlayer!=null)
              {
                     mediaPlayer.pause();
              }
              btn_play.setEnabled(true);
              btn_pause.setEnabled(false);
       }

       private void playAudio()
       {
              if(mediaPlayer!=null)
              {
                     mediaPlayer.start();
              }            
              btn_play.setEnabled(false);
              btn_pause.setEnabled(true);
              btn_stop.setEnabled(true);
       }
}


Stream Audio from Resources:  Put audio.mp3 file in raw folder of your project.*

Main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/txt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Button
        android:id="@+id/btn_resource"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/txt"
        android:text="@string/resource" >
    </Button>

    <LinearLayout
        android:id="@+id/mediaController"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
    </LinearLayout>

</RelativeLayout>

StreamAudioFromRecourcesSampleActivity:

import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.MediaController.MediaPlayerControl;
import android.widget.RelativeLayout;


public class StreamAudioFromRecourcesSampleActivity extends Activity implements MediaPlayerControl, OnClickListener, OnCompletionListener, OnPreparedListener, OnTouchListener {
    private RelativeLayout rl;
       private Button btn_resource;
    private MediaPlayer mp;
    private MediaController mc;
       private final int AUDIO = R.raw.audio;  
       private boolean isPlayed = false;
        @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);       
       
        init();
    }

       private void init() {
              // linear layout
              rl = (RelativeLayout)findViewById(R.id.main);
              rl.setOnTouchListener(this); // if touch the screen when playing the audio,
                                                               // the MediaController will be shown.
             
              // play audio button for resource audio
              btn_resource = (Button)findViewById(R.id.btn_resource);
              btn_resource.setOnClickListener(this);
             
              // media player
              mp = new MediaPlayer();
              mp.setOnCompletionListener(this);
              mp.setOnPreparedListener(this);
             
              // madia controller
              mc = new MediaController(this);
              mc.setAnchorView(findViewById(R.id.mediaController));
              mc.setMediaPlayer(this);         
             
             
       }

       private void playMedia() throws IllegalStateException, IOException
       {
              if (isPlayed)
              {                   
                     start();
              }
              else
              {
                     mp.setDataSource(getResources().openRawResourceFd(AUDIO).getFileDescriptor());
                     mp.prepare();
              }
       }
      
       @Override
       public void onClick(View v)
       {
              try
              {                   
                     playMedia();
                     setButtonEnabled(false);
              }
              catch (Exception e)
              {
                     e.printStackTrace();
              }
       }
      
       @Override
       public void onPrepared(MediaPlayer mp)
       {
              mp.start();
              mc.show();
              isPlayed = false;
       }
      
       @Override
       public void onCompletion(MediaPlayer arg0)
       {
              setButtonEnabled(true);
              isPlayed = true;
              mc.show();
       }
             private void setButtonEnabled(boolean b)
       {
              // when playing, not to push button again
              btn_resource.setEnabled(b);      
       }
       @Override
       public boolean onTouch(View v, MotionEvent event)
       {
              if (mc != null)
              {
                     mc.show();
              }
              return false;
       }

       @Override
       public boolean canPause() {return true;  }

       @Override
       public boolean canSeekBackward() {return false; }

       @Override
       public boolean canSeekForward() {return false;}

       @Override
       public int getBufferPercentage()
       {
              int percentage = (mp.getCurrentPosition() * 100) / mp.getDuration();
              return percentage;
       }

      @Override
       public int getCurrentPosition() { return mp.getCurrentPosition();   }

       @Override
       public int getDuration() {return mp.getDuration();}

       @Override
       public boolean isPlaying() {return mp.isPlaying();}

       @Override
       public void pause() {mp.pause();  }

       @Override
       public void seekTo(int pos) {mp.seekTo(pos);}

       @Override
       public void start() {mp.start();mc.show();}
      
       @Override
    protected void onDestroy()
       {
        super.onDestroy();
        mp.stop();
        mp.release();
    }

}