voice recording app - java

I am making a voice recording android app. The problem is that when I want to pause and continue the record it does not work and the app crashes. This is code :
buttonPause.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.N)
#Override
public void onClick(View view) {
try {
recording=false;
mediaRecorder.pause();
recording=false;
buttonRecord.setBackgroundResource(R.drawable.record);
Toast.makeText(getActivity(), "Recording pause",
Toast.LENGTH_LONG).show();
}catch (Exception e){
}
and this appears on log
enter image description here

Please add the log of the Error, or it's impossible to help you.
The MediaRecorder can be paused ("pause()") and resumed ("resume()"). The only case when Pause() throws an Exception is when it is called before a "start()" or after a "stop()".

Related

App crash in Android Studio 4 emulator while testing recording and play

I've met with problems while testing a recording app on the emulator(Pixel 3a API 30)
Below is the Java code that I searched for in the tutorial on Youtube.
In the video it can be tested normally.
When it comes to me, it kept crashing when I hit on the stop recording button.
//Request Runtime Permission
if (!checkPermissionFromDevice())
requestPermission();
//Init view
pl_btn = (Button)findViewById(R.id.play_btn);
rcrd_btn = (Button)findViewById(R.id.record_button);
stp_rcrd_btn = (Button)findViewById(R.id.stop_record_btn);
ps_btn = (Button)findViewById(R.id.pause_btn);
//From Android M, need request Run-time permission
rcrd_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkPermissionFromDevice()) {
pathSave = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/"
+ UUID.randomUUID().toString() + "audio_record.3gp";
setupMediaRecorder();
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IOException e) {
e.printStackTrace();
}
pl_btn.setEnabled(false);
ps_btn.setEnabled(false);
rcrd_btn.setEnabled(false);
stp_rcrd_btn.setEnabled(true);
Toast.makeText(recording_and_play_test.this, "Recording...", Toast.LENGTH_SHORT).show();
} else {
requestPermission();
}
}
});
stp_rcrd_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaRecorder.stop();
stp_rcrd_btn.setEnabled(false);
pl_btn.setEnabled(true);
rcrd_btn.setEnabled(true);
ps_btn.setEnabled(false);
}
});
pl_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ps_btn.setEnabled(true);
stp_rcrd_btn.setEnabled(false);
rcrd_btn.setEnabled(false);
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(pathSave);
mediaPlayer.prepare();
}catch (IOException e){
e.printStackTrace();
}
mediaPlayer.start();
Toast.makeText(recording_and_play_test.this, "Playing...", Toast.LENGTH_SHORT).show();
}
});
ps_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stp_rcrd_btn.setEnabled(false);
rcrd_btn.setEnabled(true);
pl_btn.setEnabled(true);
ps_btn.setEnabled(false);
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 requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO
},REQUEST_PERMISSION_CODE);
}
And here's what the activity looks like
While I hit the stop recording button while executing the recording function, the app then just crashed and restarts again.
Here's what the build log says
E/MediaRecorder: stop called in an invalid state: 4
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.adrsingingscope, PID: 7309
java.lang.IllegalStateException
at android.media.MediaRecorder.stop(Native Method)
at com.example.adrsingingscope.recording_and_play_test$2.onClick(recording_and_play_test.java:88)
at android.view.View.performClick(View.java:7448)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
This could be a problem with the path you created to save a file. These things can be easy to mess up. The media recorder has its own state and STATE 4 in which your app crashed in the state of recording. So it didn't stop and something happened in between that process so I assume it is related to saving your file to external storage.
You can find MEDIA_RECORDER_STATES here: https://android.googlesource.com/platform/frameworks/av/+/android-4.2.2_r1.2/include/media/mediarecorder.h#96
There are three things you can try.
Change your save file path
Try changing your path to a different directory. Sometimes you are trying to reach the directory you are not allowed to or it doesn't exist. More you can read in this answer: https://stackoverflow.com/a/33107120/14759470
Check your AndroidManifest.xml for permissions
Check if you wrote your permissions in AndroidManifest.xml as you should. You need WRITE_EXTERNAL_STORAGE and RECORD_AUDIO for this. In your code, it even says that from Android M (6.0) you need RUN_TIME permission. So just add them on top of your manifest file if you didn't.
Make your code better
Don't stop the recorder if it's already stopped. This will throw an exception. Don't release if already released, also an exception, and so on. So test your code for bugs, make breakpoints, and find your weak spots. It will be easier for you to find your errors. Also, check the log for more error messages since this one doesn't give us much.

Android Mediaplayer Selecttrack method fails

I am using the mediaplayer feature on Android. I basically have songs in the raw folder and I would just like to change to a new track but it fails. One music file plays and then I press a button after or during the music playing to skip to a random track but it fails.
Current code
mediaplayer.stop();
try {
mediaplayer.prepareAysn();
mediaPlayer.selectTrack(randomtrack_num - 1);
}
catch(Exception e){}
mediaplayer.start();
The error that I receive:
MediaPlayer: start called in state 64
MediaPlayer: error (-38, 0)
MediaPlayer: Error (-38,0)
I tried this without mediaplayer.stop() and still included mediaplayer.start() at the end and it would just replay the same track again.
Am I missing something?
Please let me know.
2nd Approach
After reading the document I realized this can only be done in the prepared state which I assume in my second approach it should work but it is not.
mediaPlayer.stop();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp) {
try{
mp.selectTrack(randomtrack_num - 1);
}catch(Exception e){}
mp.start();
}
});
mediaPlayer.prepareAsync();
I get this error:/MediaPlayer: Should have subtitle controller already set
Basically the same track plays again and it does not go to the selected track.
You are calling mediaplayer.start() in wrong state. Firstly read this documentation:
https://developer.android.com/reference/android/media/MediaPlayer.html
You will have a better idea of correct implementation.
EDITED:
String[] url ; // initiliaze your URL array here
MediaPlayer myMediaPlayer = new MediaPlayer();
myMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
myMediaPlayer.setDataSource(url[0]);
myMediaPlayer.prepareAsync(); // might take long! (for buffering, etc)
} catch (IOException e) {
Toast.makeText(this, "mp3 not found", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
//mp3 will be started after completion of preparing...
myMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer player) {
player.start();
}
});
Playing different track after completions
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp)
{
myMediaPlayer.reset();
/* load the new source */
myMediaPlayer.setDataSource(url[position]);//select the path according to your need
/* Prepare the mediaplayer */
myMediaPlayer.prepareAsync();
}

Android: MediaPlayer reloads remote resource

i am using the MediaPlayer class to loop music from youtube. So far no problem, but the MediaPlayer downloads the video every playback again from youtube, which causes a lot of traffic. Is there a way to let the video in the buffer of the MediaPlayer?
I'm using the following code:
try {
MediaPlayer mp = new MediaPlayer();
mp.setDataSource("http://r6---sn-4g57knsy.googlevideo.com/videoplayback?itag=18&key=yt5&ip=123.45.67.89&ipbits=0&ratebypass=yes&ms=au&source=youtube&sver=3&mt=1383664037&id=3fa390e8443132e0&expire=1383690428&sparams=gcr%2Cid%2Cip%2Cipbits%2Citag%2Cratebypass%2Csource%2Cupn%2Cexpire&fexp=935610%2C932206%2C916807%2C941242%2C916623%2C924616%2C907231%2C907240&mv=m&gcr=de&upn=9y98yq_WFEc&signature=98E548B5E368061D425FED483828E6D5AF1BBC2B.8AB359B7BA604F108D85578BC704844308E9B6EB");
mp.setLooping(true);
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mp.prepare();
} catch (Exception e) {
e.printStackTrace();
}
Thanks.
Short answer: no.
Long answer: write a simple proxy server to run on the device and cache it yourself. It's not incredibly hard, but it requires some thought to pull off seemlessly.

onPrepared() taking a long time in MediaPlayer()?

I am streaming a live .mp3 from an online source. The problem is that between prepareAsync() and onPrepared(), almost 1 minute passes. That means that prepareAsync is taking upwards of 1 minute to prepare before playback can start. The code is below:
void start1(String a){
mp.setDataSource(a);
mp.setOnPreparedListener(this);
mp.prepareAsync();
running=true;
}catch(Exception e){
noerror=false;
}
}
#Override
public void onPrepared(MediaPlayer mp1){
Log.d("in here2","okay");
//mp.start();
Log.d("in here2","okay");
}
This is happening in emulator. Is there something wrong with the code?

enquiry about MediaPlayer.setDatasource(URL);

I'm a Beginner in android programming and I want to programming mp3 app to call some mp3 files from URL, so when I show "Media Player" in android developer I put the URL in the setDataSource and it's work fine, but the problem is the Activity take a lot of time to display it and in the sometimes app will be crashed. This is the part of my code :
file_url = Mp3_Linkes[num];
//Set Source
try {
mp.setDataSource(file_url);
} catch (Exception e) {
Toast.makeText(this, "Source Error !!", Toast.LENGTH_LONG).show();
}
//Prepare
try {
mp.prepare();
}catch(Exception e)
{
Toast.makeText(this, "Prepare Error !!", Toast.LENGTH_LONG).show();
}
//Start
mp.start();
Your activity is blocking because you are calling prepare on your Main Thread (UI thread)
Instead You can use prepareAsynch and OnPreparedListener to start specially when loading from remote source:
code :
try {
mp.setDataSource(file_url);
mp.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer player) {
player.start();
}
});
mp.prepareAsync();

Categories