Android MediaRecorder recording looping back on itself - android

I have made an app which uses a MediaRecorder and a MediaPlayer, but whenever I record something and play it, it kinda loops back on itself.
e.g I say, one, two, three, four, five, six, seven, eight, nine, ten
but it plays back as one, two, three three, four four, five five five etc. it gets worse if the recording is longer?
It might be a simple bug, but I don't see it.
Here is my code :
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.CountDownTimer;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ProgressBar;
import android.widget.Switch;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
Switch switchPlay;
Button btnRecord, btnDelete;
ProgressBar pBarMetronome;
MediaRecorder mRecorder1, mRecorder2, mRecorder3, mRecorder4, mRecorder5, mRecorder6;
MediaPlayer mp1, mp2, mp3, mp4, mp5, mp6;
String sdPath = "/sdcard/Looper Recordings/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchPlay = (Switch)findViewById(R.id.switchPlay);
btnRecord = (Button)findViewById(R.id.buttonRecord);
btnDelete = (Button)findViewById(R.id.buttonDelete);
pBarMetronome = (ProgressBar)findViewById(R.id.progressBarMetronome);
clearFile();
createFile();
lineOne();
}
private void playOne(){
mp1 = new MediaPlayer();
Uri myUri = Uri.parse("/sdcard/Looper Recordings/one.mp3");
mp1.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mp1.setDataSource(getApplicationContext(), myUri);
} catch (IOException e) {
e.printStackTrace();
}
try {
mp1.prepare();
Toast.makeText(MainActivity.this, "preparing", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
mp1.start();
Toast.makeText(MainActivity.this, "play!", Toast.LENGTH_SHORT).show();
}
private void recordOne(){
mRecorder1 = new MediaRecorder();
mRecorder1.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder1.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mRecorder1.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mRecorder1.setOutputFile(sdPath+"one.mp3");
//mRecorder1.setAudioEncoder(MediaRecorder.getAudioSourceMax());
mRecorder1.setAudioEncodingBitRate(16);
mRecorder1.setAudioSamplingRate(44100);
try {
mRecorder1.prepare();
Toast.makeText(MainActivity.this, "preparing...", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, "starting...", Toast.LENGTH_SHORT).show();
mRecorder1.start();
new CountDownTimer(5000,1000){
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
mRecorder1.stop();
Toast.makeText(MainActivity.this, "Stopped!", Toast.LENGTH_SHORT).show();
}
}.start();
}
private void lineOne(){
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
recordOne();
}
});
btnRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new CountDownTimer(4000,1000){
#Override
public void onTick(long millisUntilFinished) {
btnRecord.setText(""+(millisUntilFinished/1000));
playOne();
}
#Override
public void onFinish() {
}
}.start();
}
});
switchPlay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
//ON
}else{
//OFF
}
}
});
}
private void clearFile(){
File dir = new File(Environment.getExternalStorageDirectory()+"/sdcard/Looper Recordings");
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
new File(dir, children[i]).delete();
}
}
}
private void createFile(){
File recordingDirectory = new File(Environment.getExternalStorageDirectory()+ File.separator+"Looper Recordings");
if(!recordingDirectory.exists() && !recordingDirectory.isDirectory())
{
// create empty directory
if (recordingDirectory.mkdirs())
{
Toast.makeText(MainActivity.this, "Folder for recordings created!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "Folder for recordings could not be created?", Toast.LENGTH_SHORT).show();
}
}
else
{
}
}
}
I know it's very messy but I'm still prototyping
Thanks to anyone who is willing to help!

It seems you are initializing MediaPlayer multiple times and play them simeltenously

Did you try set looping false.
private void playOne(){
if(mp1 != null && mp1.isPlaying()){
{
mp1.stop();
}
mp1 = new MediaPlayer();
mp1.setLooping(false);
Uri myUri = Uri.parse("/sdcard/Looper Recordings/one.mp3");
mp1.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mp1.setDataSource(getApplicationContext(), myUri);
} catch (IOException e) {
e.printStackTrace();
}
try {
mp1.prepare();
Toast.makeText(MainActivity.this, "preparing", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
mp1.start();
Toast.makeText(MainActivity.this, "play!", Toast.LENGTH_SHORT).show();
}

Related

Record button works only once in android audio recording application

I have developed an android app that records users voice. Its a learning app for me. However the problem is that the record button works only once and the second time when I hit record it does not stop at all. There are total four buttons Record-Stop record. Play-stop play.
The exact problem is that when second time record is pressed the stop button stays greyed out.
The third time I press record the application crashes directly.
package com.example.soundrecorder;
import android.Manifest;
import android.content.pm.PackageManager;
import android.content.pm.PermissionInfo;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
Button btnRecord, btnStopRecord, btnPlay, btnStop;
String pathsave="";
MediaRecorder mediaRecorder;
MediaPlayer mediaplayer;
final int REQUEST_PERMISSION_CODE=1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Request Runtime Permission
if(!CheckPermissionFromDevice())
requestPermissions();
//init view
btnPlay = (Button)findViewById(R.id.btnPlay);
btnRecord = (Button)findViewById(R.id.btnStartRecord);
btnStop = (Button)findViewById(R.id.btnStop);
btnStopRecord = (Button)findViewById(R.id.btnStopRecord);
btnRecord.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
if(CheckPermissionFromDevice())
{
pathsave = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"
+ UUID.randomUUID().toString()+"_audio_record.3gp";
setupMediaRecorder();
try{
mediaRecorder.prepare();
mediaRecorder.start();
}catch (IOException e){
e.printStackTrace();
}
btnPlay.setEnabled(false);
btnStop.setEnabled(false);
Toast.makeText(MainActivity.this, "Recording...", Toast.LENGTH_SHORT).show();
}
else
{
requestPermissions();
}
}
});
btnStopRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaRecorder.stop();
btnStopRecord.setEnabled(false);
btnPlay.setEnabled(true);
btnRecord.setEnabled(true);
btnStop.setEnabled(false);
}
});
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnStop.setEnabled(true);
btnStopRecord.setEnabled(false);
btnRecord.setEnabled(false);
mediaplayer = new MediaPlayer();
try{
mediaplayer.setDataSource(pathsave);
mediaplayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaplayer.start();
Toast.makeText(MainActivity.this, "Playing...", Toast.LENGTH_SHORT).show();
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnStopRecord.setEnabled(false);
btnRecord.setEnabled(true);
btnStop.setEnabled(false);
btnPlay.setEnabled(true);
if(mediaplayer !=null)
{
mediaplayer.stop();
mediaplayer.release();
setupMediaRecorder();
}
}
});
}
private void setupMediaRecorder() {
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(pathsave);
}
private void requestPermissions()
{
ActivityCompat.requestPermissions(this,new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO,
},REQUEST_PERMISSION_CODE );
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode)
{
case REQUEST_PERMISSION_CODE:
{
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
Toast.makeText(this,"Permission Granted",Toast.LENGTH_SHORT).show();
else
{
Toast.makeText(this,"Permission Denied",Toast.LENGTH_SHORT).show();
}
}
break;
}
}
private boolean CheckPermissionFromDevice()
{
int write_external_storage_result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int record_audio_result = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
return write_external_storage_result == PackageManager.PERMISSION_GRANTED && record_audio_result == PackageManager.PERMISSION_GRANTED;
}
}
There doesn't seem to be a btnStopRecord.setEnabled(true); in the btnRecord click function. If you can stop the first recording, it's probably because the stop record button is enabled by default, but when you press it, it disables itself. You should probably initialize the enabled state of your buttons too, but this should solve your problem:
public void onClick(View view) {
if(CheckPermissionFromDevice())
pathsave = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+UUID.randomUUID().toString()+"_audio_record.3gp";
setupMediaRecorder();
try{
mediaRecorder.prepare();
mediaRecorder.start();
btnStopRecord.setEnabled(true); //enable stop record
btnPlay.setEnabled(false); //shouldn't be able to play while recording too
btnRecord.setEnabled(false); //yours to see if should be able to restart record while recording, but probably not if it crashes
btnStop.setEnabled(false); //probably should be disabled too on record
//...rest of the function

I want to make sos app but errors in blinking method

I am very new to android. Following is my code and I am getting these errors.
Cannot resolve symbol params.
Variable "blinkDelay" never assigned.
When i hover the mouse over "Parameters". it says "android.hardware.Camera.Parameters Alt+Enter".
In the following code:
blinkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myString = "0101010101";
long blinkDelay 50;
for (int i = 0; i < myString.length(); i++) {
if (myString.charAt(i) == '0') {
params.setFlashMode(Parameters.FLASH_MODE_ON);
} else {
params.setFlashMode(Parameters.FLASH_MODE_OFF);
}
try {
Thread.sleep(blinkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Here is my full MainActivity.java
package com.fusion.flashlight;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
public class MainActivity extends AppCompatActivity {
private CameraManager mCameraManager;
private String mCameraId;
private ImageButton mTorchOnOffButton;
private ImageButton firstButton;
private Button blinkButton;
private Boolean isTorchOn;
private MediaPlayer media;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("MainActivity", "onCreate()");
setContentView(R.layout.activity_main);
mTorchOnOffButton = (ImageButton) findViewById(R.id.btnSwitch);
firstButton = (ImageButton) findViewById(R.id.btn1Switch);
blinkButton = (Button) findViewById(R.id.blinking);
isTorchOn = false;
Boolean isFlashAvailable = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!isFlashAvailable) {
AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
.create();
alert.setTitle("Error !!");
alert.setMessage("Your device doesn't support flash light!");
alert.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish();
System.exit(0);
}
});
alert.show();
return;
}
mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
mCameraId = mCameraManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
e.printStackTrace();
}
mTorchOnOffButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (isTorchOn) {
turnOffFlashLight();
isTorchOn = false;
} else {
turnOnFlashLight();
isTorchOn = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
blinkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myString = "0101010101";
long blinkDelay 50;
for (int i = 0; i < myString.length(); i++) {
if (myString.charAt(i) == '0') {
params.setFlashMode(Parameters.FLASH_MODE_ON);
} else {
params.setFlashMode(Parameters.FLASH_MODE_OFF);
}
try {
Thread.sleep(blinkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
public void turnOnFlashLight() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, true);
playOnOffSound();
mTorchOnOffButton.setImageResource(R.drawable.btn_on);
firstButton.setImageResource(R.drawable.btn11_on);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void turnOffFlashLight() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, false);
playOnOffSound();
mTorchOnOffButton.setImageResource(R.drawable.btn_off);
firstButton.setImageResource(R.drawable.btn11_off);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void playOnOffSound(){
media = MediaPlayer.create(MainActivity.this, R.raw.light_switch_on);
media.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
//TODO Auto-generated method stub
mp.release();
}
});
media.start();
}
#Override
protected void onStop() {
super.onStop();
if(isTorchOn){
turnOffFlashLight();
}
}
#Override
protected void onPause() {
super.onPause();
if(isTorchOn){
turnOffFlashLight();
}
}
#Override
protected void onResume() {
super.onResume();
if(isTorchOn){
turnOnFlashLight();
}
}
}
For blinkDelay, you are missing an equal symbol when assigning,
For params, I cant see where do you create that variable.
And the other, alt+Enter is for autoImporting the Parameters class by Android Studio.
Cannot resolve symbol params. params not define
Variable "blinkDelay" never assigned. blinkDelay having no initial value
long blinkDelay =50;
When i hover the mouse over "Parameters". it says
"android.hardware.Camera.Parameters Alt+Enter". Alt+Enter for import

OnclickListener force closes. not sure if its in the right place

ok so i have a template that installs an apk from the assets folder. recently ive been modding the template to accomodate features that i wanted to add, so im basically adding to code that was there already.
ive added 2 onclicklisteners and both of them fail with the error "No activity found to handle the intent"
heres what i have
package com.example.depthtiles;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.example.depthtiles.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.Toast;
public class MainActivity extends Activity {
// change this to your apk skin name
private static final String ZOOPER_APK = "Depth Zooper.apk";
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
context = this;
setContentView(R.layout.activity_main);
ScrollView sView = (ScrollView)findViewById(R.id.ScrollView02);
//Hide the Scrollbar
sView.setVerticalScrollBarEnabled(false);
sView.setHorizontalScrollBarEnabled(false);
findViewById(R.id.InstallSkinButton).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
showInstallableSkins();
}
});
findViewById(R.id.InstallIconButton).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("com.example.depthfinal.ICONBUTTON"));
}
});
findViewById(R.id.ButtonGmail).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("com.example.depthfinal.CONTACTGMAIL"));
}
});
}
private class RepairSkinAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog mDialog;
#Override
protected void onPreExecute() {
mDialog = ProgressDialog.show(context, "", "Processing...", true);
}
#Override
protected Void doInBackground(Void... nothing) {
String SDCARD_MYAPK_APK = Environment.getExternalStorageDirectory()
.getPath() + File.separator + "my_temporary_skin_apk.apk";
deleteOldSkin(SDCARD_MYAPK_APK);
saveSkinToSdCard(SDCARD_MYAPK_APK);
startAppInstaller(SDCARD_MYAPK_APK);
return null;
}
#Override
protected void onPostExecute(Void result) {
mDialog.dismiss();
finish();
}
}
/**
*
*/
private void showInstallableSkins() {
if (isSDcardAvailable()) {
new RepairSkinAsyncTask().execute();
} else {
Toast.makeText(this, "SD card not available", Toast.LENGTH_LONG)
.show();
}
}
private void deleteOldSkin(String pathToSkin) {
File file = new File(pathToSkin);
if (file.exists()) {
file.delete();
}
}
/**
* #param assetManager
* #param in
* #param out
* #param pathToSkin
*/
private void saveSkinToSdCard(String pathToSkin) {
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(ZOOPER_APK);
try {
out = new FileOutputStream(pathToSkin);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* #param pathToSkin
*/
private void startAppInstaller(String pathToSkin) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(pathToSkin)),
"application/vnd.android.package-archive");
startActivity(intent);
}
private boolean isSDcardAvailable() {
String state = Environment.getExternalStorageState();
return state.contentEquals(Environment.MEDIA_MOUNTED)
|| state.contentEquals(Environment.MEDIA_MOUNTED_READ_ONLY);
}
}
the first onclick was there from the template and works fine. the 2 that i added however do not. Im just starting out in android and im not sure if there in the right spot.
Try this..
Change this
startActivity(new Intent("com.example.depthfinal.ICONBUTTON"));
startActivity(new Intent("com.example.depthfinal.CONTACTGMAIL"));
to
startActivity(new Intent(MainActivity.this,ICONBUTTON.class));
startActivity(new Intent(MainActivity.this,CONTACTGMAIL.class));
Inside Click
findViewById(R.id.InstallIconButton).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(MainActivity.this,ICONBUTTON.class));
}
});
You can either initialise Button first like this
Button btn=(Button)findViewById(R.id.btn_st_open2);
then set listner on it like this
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// do something you want
}
});
or in your code just do casting at The OnclickListner part like this
(Button)findViewById(R.id.InstallSkinButton).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
showInstallableSkins();
}
});
hopefully it will help you thanks

Android radio streaming, the steam link doesnt play

I've followed up zvzej's post on Online radio streaming app for Android
I am encountering 2 problems:
1st.) The stream link don't play, though buttonPlay.enabled(false) does work, I also don't see the progressbar, eventhough onClick of Play it should be visible. Does this mean the script cant go beyond
playSeekBar.setVisibility(View.VISIBLE);
in startPlaying() ?
2nd.) After clicking Play, then stop, then back to play, the application force crashes, sometimes it requires more clicks, sometimes fewer.
Code:
package com.afghan.radios;
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class ArmanFMRadio extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.armanfm);
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);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("http://usa8-vn.mixstream.net:8138");
} 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.setVisibility(View.VISIBLE);
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
try {
player.prepare();
player.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}

error record and play audio in android

i've been trying to record and play recorded audio in android . I've used MediaRecorder and MediaPlayer class for the same.
My code contain 3 segments:
startrecording()
stoprecording()
playaudio
But there's an error in my code fragement and whenever i execute it ,the startrecording() function implements catch block.
package hare.krishna;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
public class Recordplay2Activity extends Activity
{
Button play1,record1,stop1;
TextView status1;
MediaRecorder m1=null;
MediaPlayer m2=null;
String path;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
play1=(Button)findViewById(R.id.play);
record1=(Button)findViewById(R.id.record);
stop1=(Button)findViewById(R.id.stop);
status1=(TextView)findViewById(R.id.status);
OnClickListener recordListener = new OnClickListener()
{
public void onClick(View v)
{
startrecording();
}
};
OnClickListener stopListener = new OnClickListener()
{
public void onClick(View v)
{
stoprecording();
}
};
OnClickListener playListener = new OnClickListener()
{
public void onClick(View v)
{
playaudio();
}
};
record1.setOnClickListener(recordListener);
stop1.setOnClickListener(stopListener);
play1.setOnClickListener(playListener);
}
public void startrecording()
{
status1.setText("GET READY FOR RECORDING");
try
{
m1=new MediaRecorder();
m1.setAudioSource(MediaRecorder.AudioSource.MIC);
m1.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
m1.setOutputFile(path);
m1.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
m1.prepare();
m1.start();
}
catch(Exception e)
{
status1.setText("ERROR IN startrecording FUNCTION ");
}
}
public void stoprecording()
{
try
{
status1.setText("TIME TO STOP MEDIA");
m1.stop();
m1.reset();
m1.release();
}
catch(Exception e)
{
status1.setText("ERROR IN stoprecording FUNCTION");
}
}
public void playaudio()
{
status1.setText("PLAYING RECORDER AUDIO");
try
{
m2=new MediaPlayer();
m2.setDataSource("/sdcard/output.3gp");
m2.prepare();
m2.start();
}
catch(Exception e)
{
System.out.println("ERROR in playaudio FUNCTION");
}
}
}
I solved it. I changed AudioEncoder from:
m1.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB)
to:
m1.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT)

Categories

Resources