I am creating a Screen Capturing App. Using MediaRecorder with MediaProjection API.
Getting Run-time Exception while stopping the recorder
Here is the code to stop Screen Capture
private void stop_recorder() {
if (virtualDisplay == null) {
return;
}
virtualDisplay.release();
if (mediaProjection != null) {
mediaProjection.unregisterCallback(projectionCallback);
mediaProjection.stop();
mediaProjection = null;
}
if (recorder != null) {
recorder.stop();
recorder.reset();
}
}
The Exception occur is
E/MediaRecorder: stop failed: -1007
java.lang.RuntimeException: stop failed.
at android.media.MediaRecorder.stop(Native Method)
The Issue is with the emulator. It does not have audio and video source.
Look android.developer doc
RuntimeException is intentionally thrown to the application, if no valid audio/video data has been received when stop() is called. This happens if stop() is called immediately after start().
Solution
Put the mediaRecorder.stop() function in try-catch block
Related
I want to have two different background music loops playing depending on the state of the app. To do so I tried that code:
private void backgroundMusicPlayer() {
if (gameMode == 0) {
if (backgroundloop2 != null) {
backgroundloop2.pause();
backgroundloop2.stop();
backgroundloop2.release();
backgroundloop2 = null;
}
backgroundloop1 = MediaPlayer.create(getContext(), R.raw.gameloop1);
backgroundloop1.setLooping(true);
backgroundloop1.start();
}
else {
if (backgroundloop1 != null) {
backgroundloop1.pause();
backgroundloop1.stop();
backgroundloop1.release();
backgroundloop1 = null;
}
backgroundloop2 = MediaPlayer.create(getContext(), R.raw.gameloop2);
backgroundloop2.setLooping(true);
backgroundloop2.start();
}
}
But I just get errors:
"MediaPlayer: start called in state 64" "MediaPlayer: pause called in
state 8" "Failed to open libwvm.so: dlopen failed: library "libwvm.so"
not found" "Media Player called in state 0, error (-38,0)"
How can I do it properly?
Why IllegalStateException in onPause()?
In Android Documentation for onPause:
IllegalStateException
If the internal player engine has not been initialized.
In the document, you can see a maximum of media player methods would throw you IllegalStateException for some reason.
So use try catch for all of your media player operations.
Android recommends looking for Exceptions while using media player object.
It is good programming practice to always look out for
IllegalArgumentException and IOException that may be thrown from the
overloaded setDataSource methods.
I am developing music play app. When user push my app to background song is playing fine. Now if user opens the camera and starts recording video from camera, I need to pause the song playing from my app .How to do this?
I expect that the app responsible for video recording will request audio focus to notify other apps that they should cease playback. If this is the case,
you can implement AudioManager.OnAudioFocusChangeListener like this:
#Override
public void onAudioFocusChange(int focusChange)
{
if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)
{
// pause playback
}
else if (focusChange == AudioManager.AUDIOFOCUS_LOSS)
{
((AudioManager)getSystemService(Context.AUDIO_SERVICE)).abandonAudioFocus(this);
doStopPlayback();
}
// else if... listen to other types of audio focus loss/ gain
}
where doStopPlayback() is your method for releasing the MediaPlayer etc.
See also this guide for media playback.
You can check it using method Camera.open(cameraId).
Creates a new Camera object to access a particular hardware camera. If the same camera is opened by other applications, this will throw a RuntimeException.
Throws RuntimeException
If opening the camera fails (For Example, if the camera is in use by another process or device policy manager has disabled the camera).
Update:
Example:
public boolean isCameraUsebyApp() {
Camera camera = null;
try {
camera = Camera.open();
} catch (RuntimeException e) {
return true;
} finally {
if (camera != null) camera.release();
}
return false;
}
You can use this method to use as but keep this thing in mind that this method first acquire the camera.
If its acquire successfully then its mean that no other application is using this camera and don't forgot to release it again otherwise you will not able to acquire it again.
Its its throws RuntimeException it means that camera is in use by another process or device policy manager has disabled the camera.
Just to be clear: this isn't about a function returning null. It's about a function throwing an Exception which turns out to be null.
throw null;
Like that.
I have a camera application which has been working fine in Ice Cream Sandwich for a while. In Gingerbread it collapses; however, I have just seen Camera.open() throw null.
try {
releaseCameraAndPreview();
mCamera = Camera.open(camera);
//and the above throws ...
} catch (Exception e) {
e.printStackTrace();
//and e is null, causing a NullPointerException
}
releaseCameraAndPreview is this:
private void releaseCameraAndPreview() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
The camera is null at this point so nothing happens.
I didn't even know it was possible to throw null. What does it mean?
Restarting the phone fixed this; I can only assume the camera got into a corrupted state somehow during testing.
Re-locks the camera to prevent other processes from accessing it. Camera objects are locked by default unless unlock() is called. Normally reconnect() is used instead.
Since API level 14, camera is automatically locked for applications in start(). Applications can use the camera (ex: zoom) after recording starts. There is no need to call this after recording starts or stops.
Check if object is locked and try unlocking it if so.
https://developer.android.com/reference/android/hardware/Camera.html#lock%28%29
Calling stop() on my MediaRecorder hangs indefinitely on the Samsung Galaxy Camera. Placing this call in a separate thread does not help the problem either.
Logcat does not show any error messages. However, running this same app does not incur any problems on the Samsung Galaxy Nexus.
This is the code surrounding my call to stop:
View.OnClickListener captureListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isRecording) {
// stop recording and release camera
mMediaRecorder.stop();
releaseMediaRecorder(); // release the MediaRecorder object
mCamera.lock(); // take camera access back from MediaRecorder
// inform the user that recording has stopped
captureButton.setText("Capture");
isRecording = false;
} else {
// initialize video camera
if (prepareVideoRecorder()) {
// Camera is available and unlocked, MediaRecorder is prepared,
// now you can start recording
mMediaRecorder.start();
// inform the user that recording has started
captureButton.setText("Stop");
isRecording = true;
} else {
// prepare didn't work, release the camera
releaseMediaRecorder();
// inform user
}
}
}
};
One thing I saw is that for some devices MediaRecorder.stop() hangs if there is no preview attached (i.e. you called Camera.stopPreview() before or maybe you never called startPreview()).
I have created a list of songs on click on the song i am able to play the song using MedaiPlayer. While one song is playing if the user clicks another song then i am stopping the media player and starting the player again. But I am getting illegalstateexception in reset(). Here is the code where I am getting the exception. How to stop a player properly? also why am i getting this exception. How to avoid it?
public void stopPlayer() {
try {
if (player != null) {
// Log.e("Trying to Stop "," Player ");
player.stop();
player.release();
player.reset();// causes IllegalstateException
player = null;
}
} catch (Exception e) {
player = null;
playerStatus = false;
e.printStackTrace();
}
}
try this :
player.reset();
player.release();
and also have a look at media player state diagram.
If you want to play again ,then use player.reset(),
player.release() means that it releases the player object so you have to re-intialise the player. So first you use reset() and then release(). release() is used when your player object no longer working. When your activity destroys release() method to be used for good practice.
Whenever you want to stop it:
if(player!=null)
{
if(player.isPlaying())
player.stop();
player.reset();//It requires again setDataSource for player object.
}
Whenever your player no longer to be needed:
if(player!=null)
{
if(player.isPlaying())
player.stop();
player.reset();//It requires again setDataSource for player object.
player.release();
player=null; // fixed typo.
}
Though the accepted answer works, This is a better way to achieve the task
private void stopSong() {
if(mediaPlayer!=null) {
if(mediaPlayer.isPlaying()) {
mediaPlayer.reset();// It requires again setDataSource for player object.
mediaPlayer.stop();// Stop it
mediaPlayer.release();// Release it
mediaPlayer = null; // Initialize it to null so it can be used later
}
}
}
Are you planning on reusing the player again, or are you done with the player? If you're done with the player, call release() and not reset(). If you plan on reusing the player, call reset() and not release().
reset() resets the player to its uninitialized state.
release() frees all resources associated with the player.
The Media Player State Diagram shows, and also states:
Calling stop() stops playback and causes a MediaPlayer in the Started, Paused, Prepared or PlaybackCompleted state to enter the Stopped state.
Once in the Stopped state, playback cannot be started until prepare() or prepareAsync() are called to set the MediaPlayer object to the Prepared state again.
That means, that after calling stop(), we should call prepare() on the same audio file if we wish to play it again. Otherwise calling start() again won't do anything.
As prepare() might throw exception, we should wrap it in a try-catch block, like this:
public void stopAudio(View view) {
mplayer.stop();
try {
mplayer.prepare();
} catch (IOException e) {
Log.e("stopAudio", "Unable to prepare() mplayer after stop()", e);
}
}