I am recording audio using AudioRecord class.I want to record audio into a particular file in my asset folder or resource folder.I think there is no problem in recording.but while reading buffer it is showing some problem(it is throwing NullPointerException).Can anyone suggest what may be the problem?
You can not save file inside Asset folder. Assets folder is read only instead of it you will have to save it in the internal or external storage of your device
Below there is a core to record the media file.
package com.example.media.record;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MediaRecorderActivity extends Activity implements OnClickListener {
Button btnPlay;
Button btnRecord;
ProgressBar progress;
MediaPlayer mPlayer;
MediaRecorder mRecorder;
String mFileName;
boolean mStartRecording = true;
boolean mStartPlaying = true;
Thread mThreadProgress;
int duration = 1;
private void onRecord(boolean start) {
if(start) {
startRecording();
}else {
stopRecording();
}
}
private void onPlay(boolean start) {
if(start) {
startPlaying();
}else {
stopPlaying();
}
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFile(mFileName);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOnErrorListener(errorListenerForRecorder);
try {
mRecorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
mRecorder.start();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error :: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
private void stopRecording() {
if(mRecorder != null) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.setOnCompletionListener(completionListener);
mPlayer.setOnErrorListener(errorListenerForPlayer);
mPlayer.prepare();
mPlayer.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void stopPlaying() {
if(mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
}
OnCompletionListener completionListener = new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
btnRecord.setEnabled(true);
btnPlay.setText("Start playing");
mStartPlaying = !mStartPlaying;
}
};
OnErrorListener errorListenerForPlayer = new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(getApplicationContext(), "Error during playing file", 3000).show();
return false;
}
};
android.media.MediaRecorder.OnErrorListener errorListenerForRecorder = new android.media.MediaRecorder.OnErrorListener() {
#Override
public void onError(MediaRecorder mr, int what, int extra) {
Toast.makeText(getApplicationContext(), "Error during recoding file", 3000).show();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnPlay = (Button)findViewById(R.id.btnPlay);
btnRecord = (Button)findViewById(R.id.btnRecord);
progress = (ProgressBar)findViewById(R.id.progressRecorder);
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
File file = new File(mFileName);
if(!file.exists()) btnPlay.setEnabled(false);
btnPlay.setOnClickListener(this);
btnRecord.setOnClickListener(this);
}
#Override
protected void onPause() {
super.onPause();
if(mRecorder != null) {
mRecorder.stop();
}
if(mPlayer != null) {
mPlayer.pause();
}
}
#Override
protected void onResume() {
super.onResume();
if(mRecorder != null) {
mRecorder.start();
}
if(mPlayer != null) {
mPlayer.start();
}
}
#Override
protected void onStop() {
super.onStop();
if(mRecorder != null) {
mRecorder.stop();
}
if(mPlayer != null) {
mPlayer.stop();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if(mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if(mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
#Override
public void onClick(View v) {
if(v == btnPlay) {
onPlay(mStartPlaying);
if(mStartPlaying) {
duration = mPlayer.getDuration();
mThreadProgress = new ThreadProgress();
mThreadProgress.start();
((Button)v).setText("Stop Playing");
btnRecord.setEnabled(false);
}
else {
((Button)v).setText("Start Playing");
btnRecord.setEnabled(true);
if(mThreadProgress != null && !mThreadProgress.isAlive()) mThreadProgress.stop();
// t.interrupt();
}
mStartPlaying = !mStartPlaying;
} else if(v == btnRecord) {
onRecord(mStartRecording);
if(mStartRecording) {
mThreadProgress = new ThreadProgress();
mThreadProgress.start();
((Button)v).setText("Stop Recording");
btnPlay.setEnabled(false);
// t.start();
}
else {
((Button)v).setText("Start Recording");
btnPlay.setEnabled(true);
// t.interrupt();
if(mThreadProgress != null && !mThreadProgress.isAlive()) mThreadProgress.stop();
}
mStartRecording = !mStartRecording;
}
}
Handler handler = new Handler(new Callback() {
#Override
public boolean handleMessage(final Message msg) {
if(msg.what == 0) {
runOnUiThread(new Runnable() {
public void run() {
progress.setProgress(msg.arg1);
}
});
}
return false;
}
});
public class ThreadProgress extends Thread implements Runnable {
public int i = 0;
#Override
public void run() {
while((!this.isInterrupted() && mPlayer != null && mPlayer.isPlaying()) || (!this.isInterrupted() && mRecorder != null)) {
try {
if(duration == 1) i+=1;
else i += 100000 /duration;
Message message = new Message();
message.what = 0;
message.arg1 = i;
handler.sendMessage(message);
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
This is the example you can record audio as well as play audio
You can store recorded file in following places
1) File directory of your app
2) External directory(SD card)
3) Network
Related
I am trying study how to use Android record and playback function.
Through Google Android record example(https://developer.android.com/guide/topics/media/mediarecorder.html), I want change the Layout and button.
But after I reset all of them, programing is not working, I do not know what is happen.
Please advise.
import android.app.Activity;
import android.content.Context;
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.widget.Button;
import java.io.IOException;
public class ArecordActivity extends Activity{
private static final String LOG_TAG = "AudioRecordTest";
private static String mFileName = null;
private RecordButton btn_record = null;
private MediaRecorder mRecorder = null;
private PlayButton btn_play = null;
private MediaPlayer mPlayer = null;
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
stopPlaying();
}
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer = null;
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
class RecordButton extends Button {
boolean mStartRecording = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
setText("Stop recording");
} else {
setText("Start recording");
}
mStartRecording = !mStartRecording;
}
};
public RecordButton(Context ctx) {
super(ctx);
setText("Start recording");
setOnClickListener(clicker);
}
}
class PlayButton extends Button {
boolean mStartPlaying = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onPlay(mStartPlaying);
if (mStartPlaying) {
setText("Stop playing");
} else {
setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
};
public PlayButton(Context ctx) {
super(ctx);
setText("Start playing");
setOnClickListener(clicker);
}
}
public ArecordActivity() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_arecord);
btn_record = new RecordButton(this);
btn_record.findViewById(R.id.button_1);
btn_play = new PlayButton(this);
btn_play.findViewById(R.id.button_2);
}
#Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
I have successfully recorded the sound from microphone and can draw recorded sound in wav form. What I need is to draw graph dynamically when I record the sound (Like heart beat monitoring graph). Below is my code to record sound
package com.example.hp.audiorecording2;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.io.IOException;
public class RecordActivity extends Activity {
Button buttonRecord;
Button buttonPlay;
String mFileName;
MediaRecorder mediaRecorder;
private MediaPlayer mPlayer = null;
private static final String LOG_TAG = "AudioRecordTest";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record);
buttonRecord = (Button) findViewById(R.id.buttonRecord);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonRecord.setOnClickListener(new View.OnClickListener() {
boolean mStartRecording = true;
#Override
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
buttonRecord.setText("Stop");
} else {
buttonRecord.setText("Start");
}
mStartRecording = !mStartRecording;
}
});
buttonPlay.setOnClickListener(new View.OnClickListener() {
boolean mStartPlaying = true;
#Override
public void onClick(View v) {
onPlay(mStartPlaying);
if (mStartPlaying) {
buttonPlay.setText("Stop playing");
} else {
buttonPlay.setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
});
}
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
stopPlaying();
}
}
private void startRecording() {
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setOutputFile(mFileName);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mediaRecorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaRecorder.start();
}
private void stopRecording() {
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer = null;
}
public RecordActivity() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
}
}
you could use getMaxAmplitude as explained in link
I have a simple class to record voice and playing it after record play file:
public class MainActivity extends Activity
{
private static final String LOG_TAG = "AudioRecordTest";
private static String mFileName = null;
private MediaRecorder mRecorder = null;
private Button startRecord, startPlaying, stopPlaying;
private MediaPlayer mPlayer = null;
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
//stopPlaying();
pausePlaying();
}
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer = null;
}
private void pausePlaying(){
mPlayer.stop();
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
public MainActivity() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
startPlaying = (Button) findViewById(R.id.buttonStartPlay);
stopPlaying = (Button) findViewById(R.id.buttonStopPlaying);
startRecord = (Button) findViewById(R.id.buttonStartRecord);
startRecord.setOnClickListener(new OnClickListener() {
boolean mStartRecording = true;
#Override
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
startRecord.setText("Stop recording");
} else {
startRecord.setText("Start recording");
}
mStartRecording = !mStartRecording;
}
});
startPlaying.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
onPlay(true);
}
});
stopPlaying.setOnClickListener(new OnClickListener() {
boolean mStartPlaying = true;
#Override
public void onClick(View v) {
onPlay(false);
}
});
}
#Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
}
I know how can I pause, but I don't know how can I run file again but from moment where I pause my file. Any ideas?
Change this :
private void pausePlaying(){
mPlayer.stop();
}
To:
private void pausePlaying(){
if(mPlayer.isPlaying()){
mPlayer.pause();
} else {
mPlayer.start();
}
}
Don't use .stop() to pause. In the MediaPlayer API you can see that .pause() would be the best option. If you reorganized
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
To happen in your onCreate method you can avoid it resetting every time.
Check out their diagram http://i.stack.imgur.com/svHrq.gif
I'm working on an App that can record en play audio using the MediaRecorder and MediaPlayer. I also want to display the value of the maxAmplitude. I tried to use the getMaxAmplitude but i cant get it work. it keeps returning 0. The recorder and the player are working properly (it's the from developer.android.com).
Can someone please help me with it.
Eventually i want to display the dB, but i think i can do that by myself once i got this working.
I'm new to android/java, so every help is welcome.
my code
public class AudioRecordTest extends Activity{
private static final String LOG_TAG = "AudioRecordTest";
protected static final String TAG = null;
private static String mFileName = null;
private RecordButton mRecordButton = null;
private MediaRecorder mRecorder = null;
private PlayButton mPlayButton = null;
private MediaPlayer mPlayer = null;
private int currentAmplitude;
public boolean activeThread;
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
stopPlaying();
}
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer = null;
}
private void startRecording() {
if (mRecorder == null) {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
}
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
activeThread = true;
mRecorder = null;
}
public void run() {
// TODO Auto-generated method stub
try {
activeThread = true;
while(activeThread){
Log.i(TAG, "onRun()" );
Thread.sleep(50);
threadHandler.sendEmptyMessage(0);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Handler threadHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
currentAmplitude = mRecorder.getMaxAmplitude();
Log.i(TAG, "handleMessage : MaxAmplitude : "+Integer.toString(currentAmplitude) );
}
};
class RecordButton extends Button {
boolean mStartRecording = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
setText("Stop recording");
} else {
setText("Start recording");
}
mStartRecording = !mStartRecording;
}
};
public RecordButton(Context ctx) {
super(ctx);
setText("Start recording");
setOnClickListener(clicker);
}
}
class PlayButton extends Button {
boolean mStartPlaying = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onPlay(mStartPlaying);
if (mStartPlaying) {
setText("Stop playing");
} else {
setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
};
public PlayButton(Context ctx) {
super(ctx);
setText("Start playing");
setOnClickListener(clicker);
}
}
public AudioRecordTest() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
}
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout ll = new LinearLayout(this);
mRecordButton = new RecordButton(this);
ll.addView(mRecordButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
mPlayButton = new PlayButton(this);
ll.addView(mPlayButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
TextView tv = new TextView(this);
ll.addView(tv,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
tv.setText(Integer.toString(currentAmplitude));
setContentView(ll);
}
#Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
}
I'm using this code. I hope it works for you!
private MediaRecorder _recorder;
private MediaPlayer _player;
private Timer _timer;
private String _path;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record);
_timer = new Timer();
prepareEvents();
}
public void prepareEvents() {
try {
Button recordButton = (Button) findViewById(R.id.buttonRecord);
Button stopButton = (Button) findViewById(R.id.buttonStop);
Button playButton = (Button) findViewById(R.id.buttonPlay);
recordButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if(_recorder == null) {
File downloadFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PODCASTS);
_path = downloadFolder.getAbsolutePath() + "/test1.aac";
_recorder = new MediaRecorder();
_recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
_recorder.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS);
_recorder.setAudioSamplingRate(48000);
_recorder.setAudioEncodingBitRate(96000);
_recorder.setAudioChannels(2);
_recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
_recorder.setOutputFile(_path);
_recorder.prepare();
_recorder.start();
_timer.schedule(new TimerTask() {
#Override
public void run() {
RecordActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
((TextView) findViewById(R.id.textViewDecibelNumber)).setText(String.valueOf(_recorder.getMaxAmplitude()));
}
});
}
},1000,1000);
}
} catch(Exception exception) {}
}
});
stopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if(_recorder != null) {
_recorder.stop();
_recorder.release();
_recorder = null;
_timer.cancel();
((TextView) findViewById(R.id.textViewDecibelNumber)).setText("0");
} else if(_player != null) {
_player.stop();
_player.release();
_player = null;
}
} catch(Exception exception) {}
}
});
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if(_recorder == null && _path != "") {
_player = new MediaPlayer();
_player.setDataSource(_path);
_player.prepare();
_player.start();
}
} catch(Exception exception) {
System.out.println(exception.getMessage());
}
}
});
} catch(Exception exception) {
System.out.println(exception.getMessage());
}
}
You should use Thread or Handler to be able to get the max amplitude value at different time. With your code, you actually called the getMaxAmplitude() method just after you start the MediaRecorder, and only once, so it is normal it will give you 0.
Here is some code I used to detect when the sound goes below a specific amplitude : http://pastebin.com/AradRpZm
I do this and it's OK for me.
I hope it help you!
public class MediaRecorder{
private MediaRecorder mRecorder = null;
private Timer timer = new Timer();
File dir;
String file;
public Activity activity;
public void startRecording() {
if (mRecorder == null) {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile(getFilename());
try {
mRecorder.prepare();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mRecorder.start();
mEMA = 0.0;
}
}
public void stopRecording() {
if (mRecorder != null) {
mRecorder.stop();
timer.cancel();
timer.purge();
mRecorder.release();
mRecorder = null;
deleteFile();
}
}
private void deleteFile() {
File sdcard = new File(file);
boolean deleted = sdcard.delete();
Log.i("Deleting File", String.valueOf(deleted));
}
#SuppressLint("SdCardPath")
private String getFilename() {
dir = new File("/sdcard", "AUDIO_RECORDERING");
if (!dir.exists()) {
dir.mkdirs();
}
file = dir.getAbsolutePath() + "/" + System.currentTimeMillis()
+ ".mp3";
return (file);
}
private double getAmplitude() {
if (mRecorder != null) {
double m = mRecorder.getMaxAmplitude();
return (m);
} else {
return 0;
}
}
public double getAmplitudeEMA() {
double amp = getAmplitude();
return amp;
}
}
i am struggling to play an shoutcast link(.pls) i succeed with mp3 and i came to know shoutcast link is not working in android. is there any possibility to play this link in android http://stream.radiosai.net:8020/
private final static String RADIO_STATION_URL = "http://stream.radiosai.net:8002/";
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private Button buttonRecord;
private Button buttonStopRecord;
private MediaPlayer player;
private InputStream recordingStream;
private RecorderThread recorderThread;
private boolean isRecording = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
buttonRecord = (Button) findViewById(R.id.buttonRecord);
buttonRecord.setOnClickListener(this);
buttonStopRecord = (Button) findViewById(R.id.buttonStopRecord);
buttonStopRecord.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
} else if (v == buttonRecord) {
recorderThread = new RecorderThread();
recorderThread.start();
buttonRecord.setEnabled(false);
buttonStopRecord.setEnabled(true);
} else if (v == buttonStopRecord) {
stopRecording();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
player.pause();
buttonRecord.setEnabled(true);
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
buttonRecord.setEnabled(false);
buttonStopRecord.setEnabled(false);
stopRecording();
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.reset();
player.setDataSource(RADIO_STATION_URL);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
private void startRecording() {
BufferedOutputStream writer = null;
try {
URL url = new URL(RADIO_STATION_URL);
URLConnection connection = url.openConnection();
final String FOLDER_PATH = Environment
.getExternalStorageDirectory().getAbsolutePath()
+ File.separator + "Songs";
File folder = new File(FOLDER_PATH);
if (!folder.exists()) {
folder.mkdir();
}
writer = new BufferedOutputStream(new FileOutputStream(new File(
FOLDER_PATH + File.separator + "listen.pls")));
recordingStream = connection.getInputStream();
final int BUFFER_SIZE = 100;
byte[] buffer = new byte[BUFFER_SIZE];
while (recordingStream.read(buffer, 0, BUFFER_SIZE) != -1
&& isRecording) {
writer.write(buffer, 0, BUFFER_SIZE);
writer.flush();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
recordingStream.close();
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void stopRecording() {
buttonStopRecord.setEnabled(false);
buttonRecord.setEnabled(true);
try {
isRecording = false;
if (recordingStream != null) {
recordingStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private class RecorderThread extends Thread {
#Override
public void run() {
isRecording = true;
startRecording();
}
};
}
Try this code, detail is here:
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class SimpleMusicStream extends Activity implements
MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener {
private String TAG = getClass().getSimpleName();
private MediaPlayer mp = null;
private Button play;
private Button pause;
private Button stop;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
play = (Button) findViewById(R.id.play);
pause = (Button) findViewById(R.id.pause);
stop = (Button) findViewById(R.id.stop);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
play();
}
});
pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
stop();
}
});
}
private void play() {
Uri myUri = Uri.parse("http://stream.radiosai.net:8002/");
try {
if (mp == null) {
this.mp = new MediaPlayer();
} else {
mp.stop();
mp.reset();
}
mp.setDataSource(this, myUri); // Go to Initialized state
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnBufferingUpdateListener(this);
mp.setOnErrorListener(this);
mp.prepareAsync();
Log.d(TAG, "LoadClip Done");
} catch (Throwable t) {
Log.d(TAG, t.toString());
}
}
#Override
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "Stream is prepared");
mp.start();
}
private void pause() {
mp.pause();
}
private void stop() {
mp.stop();
}
#Override
public void onDestroy() {
super.onDestroy();
stop();
}
public void onCompletion(MediaPlayer mp) {
stop();
}
public boolean onError(MediaPlayer mp, int what, int extra) {
StringBuilder sb = new StringBuilder();
sb.append("Media Player Error: ");
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
}
sb.append(" (" + what + ") ");
sb.append(extra);
Log.e(TAG, sb.toString());
return true;
}
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.d(TAG, "PlayerService onBufferingUpdate : " + percent + "%");
}
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:text="Play"
android:id="#+id/play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
<Button
android:text="Pause"
android:id="#+id/pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
<Button
android:text="Stop"
android:id="#+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
</LinearLayout>