Hi,

I am attached the using code for record and play the audio above. 

My Problem is......

My audio is save  music player after closing the emulator 
I don't know the reason...
But i need the recorded voice immediately play after recording

so any know reason or know how to solve the problem?....Please help me....


Thanks,


-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en
package com.varma.samples.audiorecorder;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.annotation.SuppressLint;
import android.app.Activity;
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.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

@SuppressLint("SdCardPath")
public class RecorderActivity extends Activity {
	private static final int RECORDER_SAMPLERATE = 8000;
	private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
	private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
	private AudioRecord recorder = null;
	private AudioTrack audioTrack=null;
	private Thread recordingThread = null;
	private Thread playingThread = null;
	private boolean isRecording = false;
	private boolean isPlaying = false;
	String filePath;
	short sData[];
	byte bData[];
	private File outfile = null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.main);
	    setButtonHandlers();
	    enableButtons(false);
	    enableButtonsplay(false);
	    

	    int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,
	            RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING);

	    System.out.println("BUFFER SIZE VALUE IS " + bufferSize);

	}
	private void enableButtonsplay(boolean isPlaying) {
		enableButton(R.id.play, !isPlaying);
	    enableButton(R.id.btnplaystop, isPlaying);
		
	}
	private void setButtonHandlers()
	{
	    ((Button) findViewById(R.id.btnStart)).setOnClickListener(btnClick);
	    ((Button) findViewById(R.id.btnStoprecord)).setOnClickListener(btnClick);
	    ((Button) findViewById(R.id.play)).setOnClickListener(btnClick);
	    ((Button) findViewById(R.id.btnplaystop)).setOnClickListener(btnClick);
	}

	private void enableButton(int id, boolean isEnable) {
	    ((Button) findViewById(id)).setEnabled(isEnable);
	}

	private void enableButtons(boolean isRecording) {
	    enableButton(R.id.btnStart, !isRecording);
	    enableButton(R.id.btnStoprecord, isRecording);
	    
	}
	

	int BufferElements2Rec = 1024; // want to play 2048 (2K) since 2 bytes we use only 1024
	int BytesPerElement = 2; // 2 bytes in 16bit format

	private void startRecording() {

	    recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
	            RECORDER_SAMPLERATE, RECORDER_CHANNELS,
	            RECORDER_AUDIO_ENCODING, BufferElements2Rec*BytesPerElement);

	    recorder.startRecording();
	    isRecording = true;
	    /*//filePath = Environment.getExternalStorageDirectory()
	    	    + "/Record/test_" + System.currentTimeMillis() + ".3gp";;
	    	    System.out.println("filePath: "+filePath);
*/	    	    recordingThread = new Thread(new Runnable() {

	    	        public void run() {

	            writeAudioDataToFile();

	        }
	    }, "AudioRecorder Thread");
	    recordingThread.start();
	}

	private byte[] short2byte(short[] sData)
	{
	    int shortArrsize= sData.length;
	    byte[] bytes = new byte[shortArrsize*2];

	    for (int i=0; i < shortArrsize; i++)
	    {
	        bytes[i*2] = (byte) (sData[i] & 0x00FF);
	        bytes[(i*2)+1] = (byte) (sData[i] >> 8);
	        sData[i] = 0;
	    }
	    return bytes;

	 }

	 
	private void writeAudioDataToFile() {
	    // Write the output audio in byte
		  File sd = Environment.getExternalStorageDirectory();
	        
	        sd.mkdir();
            try {
				outfile=File.createTempFile("file", ".amr",sd);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
	    short sData[] = new short[BufferElements2Rec];

	    FileOutputStream os = null;
	    try {
	        os = new FileOutputStream(outfile);
	    } catch (FileNotFoundException e) {
	        e.printStackTrace();
	    }

	    while (isRecording) {
	        // gets the voice output from microphone to byte format

	        recorder.read(sData, 0, BufferElements2Rec);

	        try {
	            // // writes the data to file from buffer
	            // // stores the voice buffer
	            byte bData[] = short2byte(sData);
	            os.write(bData, 0, BufferElements2Rec*BytesPerElement);
	            System.out.println("bData: "+bData);
	        } catch (IOException e) {
	            System.out.println(e);
	        }
	     }

	    try {
	        os.close();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	  }

	      private void stopRecording() {
	    // stops the recording activity

	    if (null != recorder) {
	        isRecording = false;

	        recorder.stop();        
	       
/*recorder.release();*/
	        
	        

	        recorder = null;
	        recordingThread = null;
	        }
	        
	      }


		private byte[] short3byte(short[] sData)
		{
		    int shortArrsize= sData.length;
		    byte[] bytes = new byte[shortArrsize*2];

		    for (int i=0; i < shortArrsize; i++)
		    {
		        bytes[i*2] = (byte) (sData[i] & 0x00FF);
		        bytes[(i*2)+1] = (byte) (sData[i] >> 8);
		        sData[i] = 0;
		    }
		    return bytes;

		 }

		 /* private void writeAudioFile() throws IOException {
			  byte[] byteData = null;
				File file = null;
				file = new File(filePath);
				byteData = new byte[(int) file.length()];
				System.out.println("bytedata--" + byteData);
				FileInputStream is = null;

		    try {
		    	is = new FileInputStream(file);
		    	is.read(byteData);
		    	System.out.println("READING CARD-- " + is + "--BYTE Data--"
						+ byteData + byteData.length);
				is.close();

		    } catch (FileNotFoundException e) {
		        e.printStackTrace();
		    }
		    int dataSize = byteData.length / 2;
			short[] shorts = byte2short(byteData);
			

			
			 while (isPlaying) {
			

				int shortLength = shorts.length;
				int shortLengthOffset2Play = 0;

				System.out.println("SHORTS Data" + shortLength);
				// Write the byte array to the track
				audioTrack.write(shorts, 0, BufferElements2Rec);
				audioTrack.play();

				shortLengthOffset2Play += BufferElements2Rec; // Wrote 512
																// ushorts

				while (shortLengthOffset2Play < shortLength) {
					try {
						Thread.sleep(50);
					} catch (InterruptedException e) {

						e.printStackTrace();
					}
					// Waiting, Simulating your condition of receiving data
					// from server...
					audioTrack.write(shorts, shortLengthOffset2Play,
							BufferElements2Rec);
					// in your case it will 0, numberofShorts(2048)
					shortLengthOffset2Play += BufferElements2Rec;
					System.out.println("shortlengthoffset --- "
							+ shortLengthOffset2Play);
					// Wrote yet another 512 shorts
				}
				
			
		}
		  }*/

		private short[] byte2short(byte[] byteD) {
			int byteArrsize = byteD.length / 2;
			short[] shorts = new short[byteArrsize];
			for (int i = 0; i < byteArrsize; i++) {
				shorts[i] = (short) (byteD[i * 2] + (byteD[(i * 2) + 1] << 8));
			}
			return shorts;



	
		  }
		private void startPlaying() {
		
			
		
			
    playingThread = new Thread(new Runnable() {

        public void run() {

        	File file =new File(filePath);

        			
        			int audioLength = (int)(file.length());
        			byte[] audio = new byte[audioLength];
        			try {
        			InputStream is =

        			new FileInputStream(file);
        			BufferedInputStream bis =

        			new BufferedInputStream(is);
        			DataInputStream dis =

        			new DataInputStream(bis);
        			// Read the file into the buffer
        			int i = 0;

        			while (dis.available() > 0) {

        			audio[i] = dis.readByte();

        			i++;

        			}

        		

        			// Close the input streams.
        			dis.close();

        		


        			 audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
        			8000,

        			AudioFormat.

        			CHANNEL_CONFIGURATION_MONO,
        			AudioFormat.

        			ENCODING_PCM_16BIT,
        			audioLength,

        			AudioTrack.

        			MODE_STREAM);
        			audioTrack.play();

        			 audioTrack.write(audio, 0, audioLength);

        			}

        			catch (Throwable t) {
        			Log.e(

        			"AudioOutput","Failed");
        			}

        }
    }, "AudioPlayer Thread");
    playingThread.start();
			
		}
		protected void stopPlaying() {
			
			if (null != audioTrack) {
				isPlaying = false;

				audioTrack.stop();        
		       
				audioTrack.release();
		        
		        

				audioTrack = null;
		        playingThread = null;
		        }
		}

	private View.OnClickListener btnClick = new View.OnClickListener() {
	    public void onClick(View v) {
	        switch (v.getId()) {
	        case R.id.btnStart: {
	            enableButtons(true);
	            enableButtonsplay(false);
	            startRecording();
	            break;
	        }
	        case R.id.btnStoprecord: {
	            enableButtons(false);
	            enableButtonsplay(false);
	            stopRecording();
	            break;
	        }
	        case R.id.play: {
	        	enableButtonsplay(true);	        	
	        	startPlaying();
	            break;
	        }
	        case R.id.btnplaystop: {
	        	enableButtonsplay(false);
	        	
	            stopPlaying();
	            break;
	        }
	        }
	    }

		
	     };

	    @Override
	   public boolean onKeyDown(int keyCode, KeyEvent event) {

	    if (keyCode == KeyEvent.KEYCODE_BACK) {

	        finish();
	    }
	    return super.onKeyDown(keyCode, event);
	   }
		
	   }

Reply via email to