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.
Related
I am trying to record from the microphone and I built a code by trying some code snippets else where but nothing happens:
Here is the code, can someone tell me how to get this working.I am new to android coding.
package com.example.helloworld;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.AudioFormat;
import android.media.AudioRecord;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import android.util.Log;
import java.io.*;
import android.os.Environment;
public class MainActivity extends Activity {
public static final int SAMPLING_RATE = 44100;
public static final int AUDIO_SOURCE = MediaRecorder.AudioSource.MIC;
public static final int CHANNEL_IN_CONFIG = AudioFormat.CHANNEL_IN_MONO;
public static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
public static final int BUFFER_SIZE = AudioRecord.getMinBufferSize(SAMPLING_RATE, CHANNEL_IN_CONFIG, AUDIO_FORMAT);
public static final String AUDIO_RECORDING_FILE_NAME = "recording.raw";
private static final String LOGTAG = "MyActivity";
private volatile boolean mStop = true;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView text = new TextView(this);
text.setText("Hello World, Ranjan");
setContentView(text);
}
/*public void run()
{
TextView text = new TextView(this);
text.setText(" hello smart mute");
}*/
//#Override
public void run() {
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
Log.v(LOGTAG, "Starting recording…");
byte audioData[] = new byte[BUFFER_SIZE];
AudioRecord recorder = new AudioRecord(AUDIO_SOURCE,
SAMPLING_RATE, CHANNEL_IN_CONFIG,
AUDIO_FORMAT, BUFFER_SIZE);
recorder.startRecording();
String filePath = Environment.getExternalStorageDirectory().getPath()
+ "/" + AUDIO_RECORDING_FILE_NAME;
BufferedOutputStream os = null;
try {
os = new BufferedOutputStream(new FileOutputStream(filePath));
} catch (FileNotFoundException e) {
Log.e(LOGTAG, "File not found for recording ", e);
}
while (!mStop) {
int status = recorder.read(audioData, 0, audioData.length);
if (status == AudioRecord.ERROR_INVALID_OPERATION ||
status == AudioRecord.ERROR_BAD_VALUE) {
Log.e(LOGTAG, "Error reading audio data!");
return;
}
try {
os.write(audioData, 0, audioData.length);
} catch (IOException e) {
Log.e(LOGTAG, "Error saving recording ", e);
return;
}
}
try {
os.close();
recorder.stop();
recorder.release();
Log.v(LOGTAG, "Recording done…");
mStop = false;
} catch (IOException e) {
Log.e(LOGTAG, "Error when releasing", e);
}
}
}
Add these to your manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Try the below code,it helps us to record,stop and play audio
public class MainActivity extends Activity {
Button play,stop,record;
private MediaRecorder myAudioRecorder;
private String outputFile = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play=(Button)findViewById(R.id.button3);
stop=(Button)findViewById(R.id.button2);
record=(Button)findViewById(R.id.button);
stop.setEnabled(false);
play.setEnabled(false);
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";;
myAudioRecorder=new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
record.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
record.setEnabled(false);
stop.setEnabled(true);
Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myAudioRecorder.stop();
myAudioRecorder.release();
myAudioRecorder = null;
stop.setEnabled(false);
play.setEnabled(true);
Toast.makeText(getApplicationContext(), "Audio recorded successfully",Toast.LENGTH_LONG).show();
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) throws IllegalArgumentException,SecurityException,IllegalStateException {
MediaPlayer m = new MediaPlayer();
try {
m.setDataSource(outputFile);
}
catch (IOException e) {
e.printStackTrace();
}
try {
m.prepare();
}
catch (IOException e) {
e.printStackTrace();
}
m.start();
Toast.makeText(getApplicationContext(), "Playing audio", Toast.LENGTH_LONG).show();
}
});
}
I am a learner and developing an Android App to play live stream. It is working properly except 1 issue. I want to show title of currently playing Track which is available on a webpge. For this purpose I have used a textView and tried to use Asynchronous Task and called a method containing a Runnable in that Asynchronous task with which I can update text of textView at an interval on 30 seconds.In runnable I called a method which loads a webpage and give its content as a string.
Problem: When it tries to update text of textView, app crashes. THANKS IN ADVANCE.
Following is my code:
import java.io.IOException;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Handler;
import java.net.URLConnection;
import java.net.URL;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import android.util.Log;
import java.net.MalformedURLException;
import android.widget.TextView;
import android.os.AsyncTask;
public class MusicAndroidActivity extends Activity {
static MediaPlayer mPlayer;
Button buttonPlay;
Button buttonStop;
Button buttonPause;
public TextView txtMessage;
private StringBuilder response;
private String text="***";
ProgressDialog progDailog;
private final static int INTERVAL = 1000 * 30; //2 minutes
Handler mHandler;
int length=0;
String url = "http://www.s8.voscast.com:9630/;stream.mp3";
private final Handler handler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonStop = (Button) findViewById(R.id.stop);
txtMessage=(TextView)findViewById(R.id.txtMessage);
buttonStop.setEnabled(false);
buttonPause=(Button) findViewById(R.id.pause);
buttonPause.setEnabled(false);
buttonPlay = (Button) findViewById(R.id.play);
buttonPlay.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
buttonPlay.setEnabled(false);
buttonStop.setEnabled(true);
buttonPause.setEnabled(true);
//txtMessage.setText("Loading...");
progDailog = ProgressDialog.show(MusicAndroidActivity.this, "", "Buffering ... \n It can take upto 1 Minute, depending upon your internet speed", true);
mPlayer.setDataSource(url);
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
try {
mPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mPlayer) {
// TODO Auto-generated method stub
mPlayer.start();
progDailog.dismiss();
LoadWebPageASYNC task = new LoadWebPageASYNC();
task.execute(new String[]{"http://khilare.com/swltest/sms.html"});
}
});
mPlayer.prepareAsync();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} //catch (IOException e) {
//Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
//}
}
});
buttonStop.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(mPlayer!=null && mPlayer.isPlaying()){
mPlayer.stop();
buttonPlay.setEnabled(true);
buttonStop.setEnabled(false);
buttonPause.setEnabled(false);
}
}
});
buttonPause.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(mPlayer!=null && mPlayer.isPlaying()){
mPlayer.pause();
length=mPlayer.getCurrentPosition();
buttonPause.setText("Resume");
//buttonPlay.setEnabled(true);
buttonStop.setEnabled(true);
buttonPlay.setEnabled(false);
//sapp();
//getHTML();
//txtMessage.setText(text);
txtMessage.setText(text);
}
else {
//mPlayer.seekTo(length);
mPlayer.start();
// mPlayer.seekTo(length);
buttonPause.setText("Pause");
}
}
});
}
protected void onDestroy() {
super.onDestroy();
// TODO Auto-generated method stub
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
private class LoadWebPageASYNC extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
getHTML();
//sapp();
txtMessage.setText(text);
return null;
}
}
private void sapp()
{
//Runnable updater1 = new Runnable() {
handler.postDelayed(new Runnable() {
//#Override
public void run() {
getHTML();
txtMessage.setText(text);
}
}, INTERVAL);
/*public void run() {
getHTML();
txtMessage.setText(text);
}
};*/
//handler.post(updater1);
}
private void getHTML()
{
try {
URLConnection connection = new URL("http://khilare.com/swltest/sms.html").openConnection();
connection.setRequestProperty("Accept-Charset", "UTF-8");
InputStream responseStream = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(responseStream));
response = new StringBuilder();
String line;
line = br.readLine();
{
response.append(line);
}
text = response.toString();
//txtMessage.setText(text);
//Log.i("Output", text);
} catch (MalformedURLException e) {
txtMessage.setText(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
txtMessage.setText(e.getMessage());
e.printStackTrace();
}
//textStreamed.setText(text);
}
}
Here is Logcat:
java.lang.SecurityException: Permission denial: writing to settings requires android.permission.WRITE_SETTINGS
at com.android.providers.settings.SettingsProvider.callFromPackage(SettingsProvider.java:645)
at android.content.ContentProvider$Transport.call(ContentProvider.java:279)
at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:273)
at android.os.Binder.execTransact(Binder.java:388)
at dalvik.system.NativeStart.run(Native Method)
05-29 10:56:45.772 302-302/? E/Parcel﹕ Reading a NULL string not supported here.
05-29 10:56:45.772 302-302/? E/Parcel﹕ Reading a NULL string not supported here.
05-29 10:56:48.462 302-302/? E/Parcel﹕ Reading a NULL string not supported here.
05-29 10:56:48.462 302-302/? E/Parcel﹕ Reading a NULL string not supported here.
05-29 10:56:50.702 302-302/? E/Parcel﹕ Reading a NULL string not supported here.
05-29 10:56:50.702 302-302/? E/Parcel﹕ Reading a NULL string not supported here.
05-29 10:56:50.712 302-302/? E/Parcel﹕ Reading a NULL string not supported here.
05-29 10:56:50.712 302-302/? E/Parcel﹕ Reading a NULL string not supported here.
05-29 10:57:01.772 28164-28569/com.prgguru.example E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:841)
Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:5969)
at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:921)
at android.view.ViewGroup.invalidateChild(ViewGroup.java:4276)
at android.view.View.invalidate(View.java:10552)
at android.view.View.invalidate(View.java:10507)
at android.widget.TextView.checkForRelayout(TextView.java:6531)
at android.widget.TextView.setText(TextView.java:3789)
at android.widget.TextView.setText(TextView.java:3643)
at android.widget.TextView.setText(TextView.java:3618)
at com.prgguru.example.MusicAndroidActivity$LoadWebPageASYNC.doInBackground(MusicAndroidActivity.java:158)
at com.prgguru.example.MusicAndroidActivity$LoadWebPageASYNC.doInBackground(MusicAndroidActivity.java:152)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:841)
I got it.
I have used a TimeTask, which calls a method UpdateGUI(); in every 10 Seconds. This method "UpdateGUI();" further calls a method "getHTML();" which load webpage's content to String text. Also this method calls myRunnable via myHandler at
myHandler.post(myRunnable);
and myRunnable set the text of textView txtMessage
To Understand the process completely, Please read this Article
The code is now:
import java.io.IOException;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Handler;
import java.net.URLConnection;
import java.net.URL;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import android.util.Log;
import java.net.MalformedURLException;
import android.widget.TextView;
import java.util.TimerTask;
import java.util.Timer;
public class MusicAndroidActivity extends Activity {
static MediaPlayer mPlayer;
Button buttonPlay;
Button buttonStop;
Button buttonPause;
public TextView txtMessage;
private StringBuilder response;
private String text="***";
ProgressDialog progDailog;
final Handler myHandler = new Handler();
int length=0;
String url = "http://www.example.com:port/;stream.mp3";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonStop = (Button) findViewById(R.id.stop);
txtMessage=(TextView)findViewById(R.id.txtMessage);
buttonStop.setEnabled(false);
buttonPause=(Button) findViewById(R.id.pause);
buttonPause.setEnabled(false);
buttonPlay = (Button) findViewById(R.id.play);
buttonPlay.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
buttonPlay.setEnabled(false);
buttonStop.setEnabled(true);
buttonPause.setEnabled(true);
progDailog = ProgressDialog.show(MusicAndroidActivity.this, "", "Buffering ... \n It can take upto 1 Minute, depending upon your internet speed", true);
mPlayer.setDataSource(url);
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
try {
mPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mPlayer) {
// TODO Auto-generated method stub
mPlayer.start();
progDailog.dismiss();
}
});
mPlayer.prepareAsync();
Timer myTimer = new Timer(); // Declared Timer
myTimer.schedule(new TimerTask() { // Started Time Task, it will repeat as per given duration (Ours is 1000 or 10 Second)
#Override
public void run() {
UpdateGUI(); // Called Method UdateGUI
} // v
}, 0, 10000); // After Every 10 Seconds
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}
}
});
buttonStop.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(mPlayer!=null && mPlayer.isPlaying()){
mPlayer.stop();
buttonPlay.setEnabled(true);
buttonStop.setEnabled(false);
buttonPause.setEnabled(false);
}
}
});
buttonPause.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(mPlayer!=null && mPlayer.isPlaying()){
mPlayer.pause();
length=mPlayer.getCurrentPosition();
buttonPause.setText("Play");
buttonStop.setEnabled(true);
buttonPlay.setEnabled(false);
}
else {
mPlayer.start();
buttonPause.setText("Pause");
}
}
});
}
protected void onDestroy() {
super.onDestroy();
// TODO Auto-generated method stub
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
private void UpdateGUI() {
getHTML();
myHandler.post(myRunnable); // Posted MyRunnable to myHandler
}
final Runnable myRunnable = new Runnable() {
public void run() {
txtMessage.setText(text); //Set txtMessage's value to text (text is a string declared above)
}
};
private void getHTML()
{
try {
URLConnection connection = new URL("http://example.com/stats/index.php").openConnection();
connection.setRequestProperty("Accept-Charset", "UTF-8");
InputStream responseStream = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(responseStream));
response = new StringBuilder();
String line;
line = br.readLine();
{
response.append(line);
}
text = response.toString();
} catch (MalformedURLException e) {
txtMessage.setText(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
txtMessage.setText(e.getMessage());
e.printStackTrace();
}
}
}
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();
}
}
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
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