send audio file to server after recording in android - android

Thanks in advance for spent Ur time on my app...
I have an application in which I require to create an audio file after clicking ona button named "RECORD" and send this file to server. The audio file must be send in any android supported audio format.
How can I achieve this...

Code For Recording in Android
main.java:
package com.example.audiosend;
import android.os.Bundle;
import android.app.Activity;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private MediaRecorder myRecorder;
private MediaPlayer myPlayer;
private String outputFile = null;
private Button startBtn;
private Button stopBtn;
private Button playBtn;
private Button stopPlayBtn;
private TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text1);
// store it to sd card
outputFile = Environment.getExternalStorageDirectory().
getAbsolutePath() + "/MyAppRecording.3gpp"; //this is the folder in which your Audio file willl save
myRecorder = new MediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setOutputFile(outputFile);
startBtn = (Button)findViewById(R.id.start);
startBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
start(v);
}
});
stopBtn = (Button)findViewById(R.id.stop);
stopBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
stop(v);
}
});
playBtn = (Button)findViewById(R.id.play);
playBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
play(v);
}
});
stopPlayBtn = (Button)findViewById(R.id.stopPlay);
stopPlayBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopPlay(v);
}
});
}
public void start(View view){
try {
myRecorder.prepare();
myRecorder.start();
} catch (IllegalStateException e) {
// start:it is called before prepare()
// prepare: it is called after start() or before setOutputFormat()
e.printStackTrace();
} catch (IOException e) {
// prepare() fails
e.printStackTrace();
}
text.setText("Recording Point: Recording");
startBtn.setEnabled(false);
stopBtn.setEnabled(true);
Toast.makeText(getApplicationContext(), "Start recording...",
Toast.LENGTH_SHORT).show();
}
public void stop(View view){
try {
myRecorder.stop();
myRecorder.release();
myRecorder = null;
stopBtn.setEnabled(false);
playBtn.setEnabled(true);
text.setText("Recording Point: Stop recording");
Toast.makeText(getApplicationContext(), "Stop recording...",
Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
// it is called before start()
e.printStackTrace();
} catch (RuntimeException e) {
// no valid audio/video data has been received
e.printStackTrace();
}
}
public void play(View view) {
try{
myPlayer = new MediaPlayer();
myPlayer.setDataSource(outputFile);
myPlayer.prepare();
myPlayer.start();
playBtn.setEnabled(false);
stopPlayBtn.setEnabled(true);
text.setText("Recording Point: Playing");
Toast.makeText(getApplicationContext(), "Start play the recording...",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stopPlay(View view) {
try {
if (myPlayer != null) {
myPlayer.stop();
myPlayer.release();
myPlayer = null;
playBtn.setEnabled(true);
stopPlayBtn.setEnabled(false);
text.setText("Recording Point: Stop playing");
Toast.makeText(getApplicationContext(), "Stop playing the recording...",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Related

Android media sound Recorder Start failed

My application got crashed whenever i press start button. Logcat says its because of start method failed. I google the error but i didn't find anything. It is giving exception at the native method Start(v);
Here is my logcat :
08-22 18:44:23.420: E/MediaRecorder(3607): start failed: -2147483648
08-22 18:44:23.420: V/MediaRecorderJNI(3607): process_media_recorder_call
08-22 18:44:23.420: W/dalvikvm(3607): threadid=1: thread exiting with uncaught exception (group=0x41234438)
08-22 18:44:23.420: E/AndroidRuntime(3607): FATAL EXCEPTION: main
08-22 18:44:23.420: E/AndroidRuntime(3607): java.lang.RuntimeException: start failed.
Here is my Code :
import java.io.File;
import java.io.IOException;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private MediaRecorder myRecorder;
private MediaPlayer myPlayer;
private File outputFile = null;
private AudioTrack mAudioTrack;
private Button startBtn;
private Button stopBtn;
private Button playBtn;
private Button stopPlayBtn;
private Spinner sp;
private TextView text;
public SoundPool spl;
public int explosion = 0;
private Button playMod;
private int sampleRate = 8000;
private Uri newUri;
AudioManager audioManager;
int counter;
float actVolume, maxVolume, volume;
boolean loaded = false;
private static final String TAG = "SoundRecordingActivity";
String [] singers = {"Atif Aslam" , "Arijit Singh" , "Shreya Goshal"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text1);
sp = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> adp=new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line,singers);
adp.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
sp.setAdapter(adp);
// store it to sd card
//outFile = Environment.getExternalStorageDirectory().
// getAbsolutePath() + "/AudioRecord.3gpp";
File sampleDir = Environment.getExternalStorageDirectory();
try {
outputFile = File.createTempFile("sound", ".m4a", sampleDir);
} catch (IOException e) {
Toast.makeText(this, "No Memory Card Inserted", Toast.LENGTH_LONG).show();
Log.e(TAG, "sdcard access error");
return;
}
myRecorder = new MediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setOutputFile(outputFile.getAbsolutePath());
startBtn = (Button)findViewById(R.id.start);
startBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
start(v);
}
});
stopBtn = (Button)findViewById(R.id.stop);
stopBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
stop(v);
}
});
playBtn = (Button)findViewById(R.id.play);
playBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
play(v);
}
});
stopPlayBtn = (Button)findViewById(R.id.stopPlay);
stopPlayBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopPlay(v);
}
});
playMod = (Button)findViewById(R.id.button1);
playMod.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
playModified(v);
}
});
}
public void start(View view){
try {
myRecorder.prepare();
myRecorder.start();
} catch (IllegalStateException e) {
// start:it is called before prepare()
// prepare: it is called after start() or before setOutputFormat()
e.printStackTrace();
} catch (IOException e) {
// prepare() fails
e.printStackTrace();
}
text.setText("Recording Point: Recording");
startBtn.setEnabled(false);
stopBtn.setEnabled(true);
Toast.makeText(getApplicationContext(), "Start recording...",
Toast.LENGTH_SHORT).show();
}
public void stop(View view){
try {
myRecorder.stop();
myRecorder.release();
myRecorder = null;
stopBtn.setEnabled(false);
playBtn.setEnabled(true);
text.setText("Recording Point: Stop recording");
Toast.makeText(getApplicationContext(), "Stop recording...",
Toast.LENGTH_SHORT).show();
/////////////////////////////////////
// addRecordingToMediaLibrary();
//////////////////////////////////////
} catch (IllegalStateException e) {
// it is called before start()
e.printStackTrace();
} catch (RuntimeException e) {
// no valid audio/video data has been received
e.printStackTrace();
}
}
public void play(View view) {
try{
myPlayer = new MediaPlayer();
myPlayer.setDataSource(outputFile.getAbsolutePath());
myPlayer.prepare();
myPlayer.start();
playBtn.setEnabled(false);
stopPlayBtn.setEnabled(true);
text.setText("Recording Point: Playing");
Toast.makeText(getApplicationContext(), "Start play the recording...",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stopPlay(View view) {
try {
if (myPlayer != null) {
myPlayer.stop();
myPlayer.release();
myPlayer = null;
playBtn.setEnabled(true);
stopPlayBtn.setEnabled(false);
text.setText("Recording Point: Stop playing");
Toast.makeText(getApplicationContext(), "Stop playing the recording...",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You save the temporary file as type, m4a:
outputFile = File.createTempFile("sound", ".m4a", sampleDir);
but you have the wrong output format (3gp):
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
Solution:
If you'd like to save the recorded file as a 3gp format, you'd have to save the file as:
outputFile = File.createTempFile("sound", ".3gp", sampleDir);
else, If you'd like to save as an m4a format, you'd have to change the output format as follows:
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
Here's a list of the available formats
I had the same problem. Because I also have MediaPlayer, I solve this problem by the code:
mediaPlayer.setAudioStreamType(AudioManager.ADJUST_LOWER);
this solve my problem.

Media player not running

I am trying to run a mp3 file using media player.It compiles fine,but it is not playing the mp3 file.Even when i checked the isPlaying(),it returns false. Please tell me what is the problem with it. This is the code:
package com.example.soundplayer;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
/**
* Variables
*/
MediaPlayer mp = null;
String hello = "Hello!";
String goodbye = "GoodBye!";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
* Talking with the buttonHello
*/
final Button buttonHello = (Button) findViewById(R.id.idHello);
buttonHello.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
managerOfSound(hello);
} // END onClick()
}); // END buttonHello
}
/**
* Manager of Sounds
*/
protected void managerOfSound(String theText) {
mp = MediaPlayer.create(MainActivity.this, R.raw.sound);
mp = new MediaPlayer();
if (theText.equals(hello))
{
MediaPlayer.create(this, R.raw.sound);
mp.setVolume(1.0F, 1.0F);
mp.reset();
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (mp != null) {
mp.start();
}
if(mp.isPlaying()== true){
Toast.makeText(this, "mp is playing ", Toast.LENGTH_LONG).show();}
}
}
}
try below code
protected void managerOfSound(String theText) {
mp = MediaPlayer.create(MainActivity.this, R.raw.sound);
mp.setVolume(1.0F, 1.0F);
if (theText.equals(hello))
{
if (mp != null) {
mp.start();
}
if(mp.isPlaying()== true){
Toast.makeText(this, "mp is playing ", Toast.LENGTH_LONG).show();}
}
}

muting one audio and playing other audio in its place (VideoView)

package z.x;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.VideoView;
public class AsdqweActivity extends Activity {
/** Called when the activity is first created. */
VideoView myVideoView;
TextView translation;
String SrcPath = "/sdcard/bunny.MP4",txtdisplay="";
Thread Thread1,Thread2;
Button tag;
int count=0,tstart=-1,tend=0;
AudioManager am;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myVideoView = (VideoView) findViewById(R.id.newVideoView);
translation= (TextView) findViewById(R.id.translation);
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(myVideoView);
myVideoView.setMediaController(mediaController);
myVideoView.setKeepScreenOn(true);
Runnable runnable = new VideoPlayer();
Thread2= new Thread(runnable);
Thread2.start();
runnable = new CountDownRunner();
Thread1= new Thread(runnable);
Thread1.start();
runnable = new AudioPlayer();
Thread1= new Thread(runnable);
Thread1.start();
am =
tag = (Button) findViewById(R.id.start);
tag.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
//how to change the text on the button????????
if(count%2==0)
{
tstart=myVideoView.getCurrentPosition();
System.out.println("tag starts here: "+ tstart);
myVideoView.pause();
tend=tstart+1000;
count++;
if((tstart+1000)>myVideoView.getDuration())
{
tend=myVideoView.getDuration();
count++;
}
}
else
{
tend = myVideoView.getCurrentPosition();
if(tend>=(tstart+1000)){
System.out.println("tag ends here: "+ tend);
count++;
myVideoView.pause();
}
else
{
System.out.println("invalid tagging");
}
tstart=-1;
}
}
});
myVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
public void onCompletion(MediaPlayer mp)
{
Log.v("log_tag", "On Completion");
try {
Thread1.join();
Thread2.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//r.stopThread();
finish();
}
});
}
class VideoPlayer implements Runnable{
public void run()
{
myVideoView.requestFocus();
myVideoView.setVideoPath(SrcPath);
myVideoView.start();
}
}
class AudioPlayer implements Runnable{
public AudioPlayer() {
// TODO Auto-generated constructor stub
}
public void run()
{
/*myVideoView.setsetvolume(0,0);
audio.requestFocus();
audio.setVideoPath(SrcPathaudio);
audio.start();*/
}
}
class CountDownRunner implements Runnable
{
File file = new File("/sdcard/harsh.srt");
long r=0;
RandomAccessFile rand;
public CountDownRunner() {
// TODO Auto-generated constructor stub
if(!file.exists())
{
System.out.println("File does not exist.");
System.exit(0);
}
try {
rand = new RandomAccessFile(file,"r");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
translation = (TextView)findViewById(R.id.translation);
}
public void run()
{
// Get the object of DataInputStream
while(!Thread.currentThread().isInterrupted())
{
try
{
doWork();
Thread.sleep(100);
}catch (InterruptedException e)
{
Thread.currentThread().interrupt();
e.printStackTrace();
}catch(Exception e)
{
e.printStackTrace();
}
}
closeRandFile();
}
public void closeRandFile(){
try {
rand.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void doWork(){
runOnUiThread(new Runnable() {
public void run() {
try{
rand.seek(r);
//If it returns milliseconds, divide by 1000
int playTime = myVideoView.getCurrentPosition();
long t1=0,t2=0;
int i=0,j=0;
/* String textValue = "i havent entered it yet";
System.out.println(playTime);
if(playTime<15000){
textValue = "its still not 15000";
System.out.println(textValue);
}else if(playTime>3000)
{textValue = "its more than 15000";}*/
////////////////////////////////////
try{
// Open the file that is the first
// command line parameter
String strLine;
//Read File Line By Line
while(((strLine = rand.readLine()) != null)&&((strLine=="")))
{
System.out.println(strLine+" line 184");
}
if(strLine != null)
{
i = Integer.parseInt(strLine);
System.out.println(strLine+" line 189");
if(i>j){
if((strLine = rand.readLine()) != null)
{
//02:03:24,100 --> 02:03:25,500
//String substring(int startIndex, int endIndex)
int h =Integer.parseInt(strLine.substring(0,2));
int m =Integer.parseInt(strLine.substring(3,5));
int s =Integer.parseInt(strLine.substring(6,8));
int ms=Integer.parseInt(strLine.substring(9,12));
t1 = (((((h*60)+m)*60)+s)*1000)+ms ;
System.out.println("start of this text time "+t1);
int l = strLine.indexOf("-->")+4;
h =Integer.parseInt(strLine.substring(l+0,l+2));
m =Integer.parseInt(strLine.substring(l+3,l+5));
s =Integer.parseInt(strLine.substring(l+6,l+8));
ms=Integer.parseInt(strLine.substring(l+9,l+12));
t2 = (((((h*60)+m)*60)+s)*1000)+ms ;
System.out.println("end of this text time "+t2);
}
if((playTime<=t2)&&(playTime>=t1)){
while (((strLine = rand.readLine()) != null)&&(strLine!="")){
// Print the content on the console
txtdisplay=txtdisplay+strLine;
}
System.out.println(txtdisplay);
r=rand.getFilePointer();
translation.setText(txtdisplay);
}
txtdisplay="";
}
}
//Close the input stream
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
//////////////////////////////////////
}catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
}
I am new here. I was asked by my professor to play other audio while the same video is being played(for example a person doesn't understand English and wants the the app to play french ). I have used video view. One possible method was to mute the present audio and play the french audio stored in my sdcard. but video view supports no muting( i couldn't find one). I read that i have to go for media player instead of video view.
Please help...!! what should i do... Thanks in advance.
if you want to get access to the MediaPlayer of a VideoView you have to call MediaPlayer.OnPreparedListener and MediaPlayer.OnCompletionListener, then you can call setVolume(0f, 0f); function to set the volume to 0.
Do this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
VideoView videoView = (VideoView)this.findViewById(R.id.VVSimpleVideo);
MediaController mc = new MediaController(this);
mc.setAnchorView(videoView);
mc.setMediaPlayer(videoView);
videoView.setMediaController(mc);
String _path = "/mnt/sdcard/Movies/video5.mp4";
videoView.setVideoPath(_path);
videoView.setOnPreparedListener(PreparedListener);
videoView.requestFocus();
//Dont start your video here
//videoView.start();
}
MediaPlayer.OnPreparedListener PreparedListener = new MediaPlayer.OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer m) {
try {
if (m.isPlaying()) {
m.stop();
m.release();
m = new MediaPlayer();
}
m.setVolume(0f, 0f);
m.setLooping(false);
m.start();
} catch (Exception e) {
e.printStackTrace();
}
}
};

Android Media player not playing next stream [duplicate]

I use the following code to record audio files and play. I have a resume function which starts recording again. The audio files are stored in sdcard. My problem is, the files get stored in the sdcard but the file alone play. I need to play all the recorded files one after another. Give suggestions. I am running out of time...
ReadSDData.java
package com.fsp.audio;
import java.io.File;
import java.util.ArrayList;
import android.os.Environment;
import android.util.Log;
public class ReadSDDatas {
public String filePath()
{
String newFolderName="/MyAudio";
String extstoredir=Environment.getExternalStorageDirectory().toString();
String newPath=extstoredir+newFolderName;
return newPath;
}
public String getCombineFile()
{
String newFolderName="/MyComAudio";
String extstoredir=Environment.getExternalStorageDirectory().toString();
String path=extstoredir+newFolderName;
File myNewPath=new File(path);
if(!myNewPath.exists())
{
myNewPath.mkdir();
}
String audname="ComAudio";
String ext=".3gp";
File audio=new File(myNewPath,audname+ext);
if(audio.exists())
{
audio.delete();
}
String audpath=path+"/"+audname+ext;
Log.d("Combined audio file",audpath);
return audpath;
}
public ArrayList<String> getFileNames()
{
ArrayList<String> names=new ArrayList<String>();
names.clear();
String path=filePath();
File f=new File(path);
if(f.isDirectory())
{
File[] files=f.listFiles();
for(int i=0;i<files.length;i++)
{
System.out.println("File Name======>>>"+files[i].getName());
names.add(files[i].getName().toString().trim());
}
}
return names;
}
public ArvrayList<String> getFullAudioPath()
{
ArrayList<String> fullPath=new ArrayList<String>();
fullPath.clear();
String path=filePath();
File f=new File(path);
if(f.isDirectory())
{
File[] files=f.listFiles();
for(int i=0;i<files.length;i++)
{
String fpath=path+File.separator+files[i].getName().toString().trim();
System.out.println("File Full Path======>>>"+fpath);
fullPath.add(fpath);
}
}
return fullPath;
}
}
AudioResume1.java
package com.fsp.audio;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class AudioResume1 extends Activity {
ArrayList<String> audNames=new ArrayList<String>();
ArrayList<String> audFullPath=new ArrayList<String>();
byte fileContent[];
Button record=null;
Button stoprec=null;
Button play=null;
public MediaPlayer player=null;
public MediaRecorder recorder=null;
int cou=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
record=(Button)findViewById(R.id.recBtn);
stoprec=(Button)findViewById(R.id.stopBtn);
play=(Button)findViewById(R.id.playBtn);
record.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
System.out.println("********** Stated Recording **********");
recorder=new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
String path=audioFilePath();
System.out.println("Recording Path===========>>>"+path);
recorder.setOutputFile(path);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try
{
recorder.prepare();
recorder.start();
}
catch (IllegalStateException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
stoprec.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
System.out.println("********** Stoped Recording **********");
recorder.stop();
recorder.release();
recorder=null;
}
});
play.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
getAudioNames();
readAudioAsStream();
}
});
}
public void readAudioAsStream()
{
getAudioPath();
File f;
FileInputStream ins = null;
ReadSDDatas rds=new ReadSDDatas();
try
{
String comfile=rds.getCombineFile();
//FileOutputStream fos=new FileOutputStream(comfile);
Log.d("combined file",comfile);
File file=new File(comfile);
RandomAccessFile raf = new RandomAccessFile(file, "rw");
Log.d("path size",Integer.toString(audFullPath.size()));
for(int i=0;i<audFullPath.size();i++)
{
String filepath=audFullPath.get(i);
Log.d("Filepath",filepath);
f=new File(audFullPath.get(i));
fileContent = new byte[(int)f.length()];
ins=new FileInputStream(audFullPath.get(i));
int numofbytes=ins.read(fileContent);
System.out.println("Number Of Bytes Read===========>>>"+numofbytes);
raf.seek(file.length());
raf.write(fileContent);
}
}
catch (FileNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
playAudio();
/*for(int i=0;i<audFullPath.size();i++)
{
Log.d("fullpathsize",Integer.toString(audFullPath.size()));
playAudio(audFullPath.get(i));
}*/
}
public void playAudio()
{
//Log.d("value of path",path);
/*String newFolderName="/MyComAudio";
String extstoredir=Environment.getExternalStorageDirectory().toString();
String filename="ComAudio.3gp";
String path1=extstoredir+newFolderName+filename;
Log.d("path1",path1);*/
String path="/sdcard/MyComAudio/ComAudio.3gp";
player= new MediaPlayer();
try
{
player.setDataSource(path);
player.prepare();
player.start();
}
catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalStateException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void getAudioPath()
{
ReadSDDatas rds=new ReadSDDatas();
audFullPath=rds.getFullAudioPath();
}
public void getAudioNames()
{
ReadSDDatas rds=new ReadSDDatas();
audNames=rds.getFileNames();
}
public String audioFilePath()
{
String newFolderName="/MyAudio";
String extstoredir=Environment.getExternalStorageDirectory().toString();
String path=extstoredir+newFolderName;
File myNewPath=new File(path);
if(!myNewPath.exists())
{
myNewPath.mkdir();
}
cou++;
String audname="RecAudio";
String ext=".3gp";
File audio=new File(myNewPath,audname+Integer.toString(cou)+ext);
if(audio.exists())
{
audio.delete();
}
String audpath=path+File.separator+audname+Integer.toString(cou)+ext;
return audpath;
}
}
You can use MediaPlayer.onCompletionListener to listen to the event when a track ends, so that you can play the next one
UPDATE
player.setDataSource(path);
player.prepare();
player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer player) {
player.stop();
// play next audio file
}
});
player.start();
UPDATE 2
Your code in the comment won't work, this could be a solution:
int i = 0;
//somewhere in your activity you start playing your first file
playAudio("/sdcard/MyAudio/RecAudio"+i+".3gp");
public void playAudio(path) {
player.setDataSource(path);
player.prepare();
player.setOnCompletionListener(new OnCompletionListener() {
#Override public void onCompletion(MediaPlayer mp) {
player.stop();
if(i < numberOfFiles) {
i++;
playAudio("/sdcard/MyAudio/RecAudio"+i+".3gp");
} else i = 0;
}
});
player.start();
}
Yes this code will work fine but i have implemented differently and this will work more fine as given code
because if you play next file inside setOnCompletionListener method then it will call only single time i.e when playing first file it will call completion method and play another file but this time it will not call so you need to create new instance . dont worry just forget use
this
mc = new CountDownTimer(cownDownTime, 1000) {
public void onFinish() {
Log.i("call data hrer","aao bhai");
//initlize();
//updateText();
//startPlayProgressUpdater();
}
i.e play next file inside the Countdown timer finish() method it will run efficiently

Playing audio files one after another in android

I use the following code to record audio files and play. I have a resume function which starts recording again. The audio files are stored in sdcard. My problem is, the files get stored in the sdcard but the file alone play. I need to play all the recorded files one after another. Give suggestions. I am running out of time...
ReadSDData.java
package com.fsp.audio;
import java.io.File;
import java.util.ArrayList;
import android.os.Environment;
import android.util.Log;
public class ReadSDDatas {
public String filePath()
{
String newFolderName="/MyAudio";
String extstoredir=Environment.getExternalStorageDirectory().toString();
String newPath=extstoredir+newFolderName;
return newPath;
}
public String getCombineFile()
{
String newFolderName="/MyComAudio";
String extstoredir=Environment.getExternalStorageDirectory().toString();
String path=extstoredir+newFolderName;
File myNewPath=new File(path);
if(!myNewPath.exists())
{
myNewPath.mkdir();
}
String audname="ComAudio";
String ext=".3gp";
File audio=new File(myNewPath,audname+ext);
if(audio.exists())
{
audio.delete();
}
String audpath=path+"/"+audname+ext;
Log.d("Combined audio file",audpath);
return audpath;
}
public ArrayList<String> getFileNames()
{
ArrayList<String> names=new ArrayList<String>();
names.clear();
String path=filePath();
File f=new File(path);
if(f.isDirectory())
{
File[] files=f.listFiles();
for(int i=0;i<files.length;i++)
{
System.out.println("File Name======>>>"+files[i].getName());
names.add(files[i].getName().toString().trim());
}
}
return names;
}
public ArvrayList<String> getFullAudioPath()
{
ArrayList<String> fullPath=new ArrayList<String>();
fullPath.clear();
String path=filePath();
File f=new File(path);
if(f.isDirectory())
{
File[] files=f.listFiles();
for(int i=0;i<files.length;i++)
{
String fpath=path+File.separator+files[i].getName().toString().trim();
System.out.println("File Full Path======>>>"+fpath);
fullPath.add(fpath);
}
}
return fullPath;
}
}
AudioResume1.java
package com.fsp.audio;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class AudioResume1 extends Activity {
ArrayList<String> audNames=new ArrayList<String>();
ArrayList<String> audFullPath=new ArrayList<String>();
byte fileContent[];
Button record=null;
Button stoprec=null;
Button play=null;
public MediaPlayer player=null;
public MediaRecorder recorder=null;
int cou=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
record=(Button)findViewById(R.id.recBtn);
stoprec=(Button)findViewById(R.id.stopBtn);
play=(Button)findViewById(R.id.playBtn);
record.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
System.out.println("********** Stated Recording **********");
recorder=new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
String path=audioFilePath();
System.out.println("Recording Path===========>>>"+path);
recorder.setOutputFile(path);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try
{
recorder.prepare();
recorder.start();
}
catch (IllegalStateException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
stoprec.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
System.out.println("********** Stoped Recording **********");
recorder.stop();
recorder.release();
recorder=null;
}
});
play.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
getAudioNames();
readAudioAsStream();
}
});
}
public void readAudioAsStream()
{
getAudioPath();
File f;
FileInputStream ins = null;
ReadSDDatas rds=new ReadSDDatas();
try
{
String comfile=rds.getCombineFile();
//FileOutputStream fos=new FileOutputStream(comfile);
Log.d("combined file",comfile);
File file=new File(comfile);
RandomAccessFile raf = new RandomAccessFile(file, "rw");
Log.d("path size",Integer.toString(audFullPath.size()));
for(int i=0;i<audFullPath.size();i++)
{
String filepath=audFullPath.get(i);
Log.d("Filepath",filepath);
f=new File(audFullPath.get(i));
fileContent = new byte[(int)f.length()];
ins=new FileInputStream(audFullPath.get(i));
int numofbytes=ins.read(fileContent);
System.out.println("Number Of Bytes Read===========>>>"+numofbytes);
raf.seek(file.length());
raf.write(fileContent);
}
}
catch (FileNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
playAudio();
/*for(int i=0;i<audFullPath.size();i++)
{
Log.d("fullpathsize",Integer.toString(audFullPath.size()));
playAudio(audFullPath.get(i));
}*/
}
public void playAudio()
{
//Log.d("value of path",path);
/*String newFolderName="/MyComAudio";
String extstoredir=Environment.getExternalStorageDirectory().toString();
String filename="ComAudio.3gp";
String path1=extstoredir+newFolderName+filename;
Log.d("path1",path1);*/
String path="/sdcard/MyComAudio/ComAudio.3gp";
player= new MediaPlayer();
try
{
player.setDataSource(path);
player.prepare();
player.start();
}
catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalStateException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void getAudioPath()
{
ReadSDDatas rds=new ReadSDDatas();
audFullPath=rds.getFullAudioPath();
}
public void getAudioNames()
{
ReadSDDatas rds=new ReadSDDatas();
audNames=rds.getFileNames();
}
public String audioFilePath()
{
String newFolderName="/MyAudio";
String extstoredir=Environment.getExternalStorageDirectory().toString();
String path=extstoredir+newFolderName;
File myNewPath=new File(path);
if(!myNewPath.exists())
{
myNewPath.mkdir();
}
cou++;
String audname="RecAudio";
String ext=".3gp";
File audio=new File(myNewPath,audname+Integer.toString(cou)+ext);
if(audio.exists())
{
audio.delete();
}
String audpath=path+File.separator+audname+Integer.toString(cou)+ext;
return audpath;
}
}
You can use MediaPlayer.onCompletionListener to listen to the event when a track ends, so that you can play the next one
UPDATE
player.setDataSource(path);
player.prepare();
player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer player) {
player.stop();
// play next audio file
}
});
player.start();
UPDATE 2
Your code in the comment won't work, this could be a solution:
int i = 0;
//somewhere in your activity you start playing your first file
playAudio("/sdcard/MyAudio/RecAudio"+i+".3gp");
public void playAudio(path) {
player.setDataSource(path);
player.prepare();
player.setOnCompletionListener(new OnCompletionListener() {
#Override public void onCompletion(MediaPlayer mp) {
player.stop();
if(i < numberOfFiles) {
i++;
playAudio("/sdcard/MyAudio/RecAudio"+i+".3gp");
} else i = 0;
}
});
player.start();
}
Yes this code will work fine but i have implemented differently and this will work more fine as given code
because if you play next file inside setOnCompletionListener method then it will call only single time i.e when playing first file it will call completion method and play another file but this time it will not call so you need to create new instance . dont worry just forget use
this
mc = new CountDownTimer(cownDownTime, 1000) {
public void onFinish() {
Log.i("call data hrer","aao bhai");
//initlize();
//updateText();
//startPlayProgressUpdater();
}
i.e play next file inside the Countdown timer finish() method it will run efficiently

Categories

Resources