using buffering in Android MediaPlayer for playing mp3 - android

I have an url to mp3 file in the internet and want to play it in my app. Now i'm doing it as follows:
private void processPlayRequest(String url) {
if (mPlayer != null) {
mPlayer.stop();
mPlayer.reset();
mPlayer.release();
}
tryToGetAudioFocus();
if (mAudioFocus == AudioFocus.Focused) {
mPlayer = MediaPlayer.create(this, Uri.parse(url));
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mPlayer.setOnPreparedListener(this);
mPlayer.setOnCompletionListener(this);
mPlayer.setOnErrorListener(this);
}
}
It works, but it seems without buffering, i.e. playback begins only after entire mp3 file has been dowloaded. I want to start playback when it becomes possible for faster performance. So i need to use buffering. Is it possible to achieve?

You need to add a MediaPlayer.OnPreparedListener, and call MediaPlayer.prepareAsync(), then call start() from the onPrepared() callback.
You're calling start, reset, release in an incorrect fashion. Why bother starting, if you're going to immediately reset and release?
There's some pretty decent documentation around how to use the class in the developer docs.

Related

MediaPlayer returns error (1, -2147483648) after several app re-runs

I am writing an app that streams videos from the network using MediaPlayer and SurfaceView.
All is working fine most of the time but I've noticed that after some repeated app restarts and debugging I am not able to stream anymore files.
I close and restart the app, rebuild and run, closing and uninstalling it from the device.. nothing helps.
When the issue happens I am getting this error from the MediaPlayer (Unknown error):
E/MediaPlayer﹕ error (1, -2147483648)
The only thing that let me return to normal behaviour so that everything is working and the streaming is good is restarting the device. No code change and no other steps, just restart and re-run the app (not ever re-installing it..)
Creating the MediaPlayer object as follow:
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDisplay(mSurfaceHolder);
mMediaPlayer.setDataSource(getContext(), mVideoUrl);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(mRunLopping);
mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnErrorListener(this);
mMediaPlayer.prepareAsync();
Maybe something with global device resources? caching? any clue will help.
This is how I do it, each time the MediaPlayer is called...not sure if it's the correct way but I had the same thing happening and this helped. Looks like your code might be stacking MediaPlayer instances on top of each other.
public static MediaPlayer mPlayer = null;
void createMediaPlayerIfNeeded() {
if (mPlayer == null) {
mPlayer = new MediaPlayer();
mPlayer.setOnPreparedListener(this);
mPlayer.setOnCompletionListener(this);
mPlayer.setOnErrorListener(this);
} else
mPlayer.reset();
}
}
Stopping the MediaPLayer:
if (mPlayer != null) {
mPlayer.reset();
mPlayer.release();
mPlayer = null;
}

Is it possible to reduce the period between audio tracks being played with MediaPlayer?

I have a number of audio tracks that I need to play in sequence. I'm using MediaPlayer's OnCompletionListener as follows:
public void OnCompletion(MediaPlayer mp)
{
_completed++;
mp.Reset();
if (_completed < _tracks.Length)
{
try
{
AssetFileDescriptor afd = _context.Resources.OpenRawResourceFd(_tracks[_completed]);
if (afd != null)
{
mp.SetDataSource(afd.FileDescriptor, afd.StartOffset, afd.Length);
afd.Close();
mp.Prepare();
mp.Start();
}
}
catch (Exception ex)
{
throw;
}
}
}
This works, but there is a noticeable delay between tracks. I'd like to reduce that period to as close to zero as possible. Is this possible?
MediaPlayer "chaining" was added with API level 16 (Jellybean). The method you'd be interested in is setNextMediaPlayer(MediaPlayer next):
Set the MediaPlayer to start when this MediaPlayer finishes playback (i.e. reaches the end of the stream). The media framework will attempt to transition from this player to the next as seamlessly as possible. The next player can be set at any time before completion. The next player must be prepared by the app, and the application should not call start() on it.
Not with the standard android player though there were many requests to add gapless playback - https://code.google.com/p/android/issues/detail?id=3461
You can try to create and prepare a second instance of MediaPlayer and switch them quickly in the OnCompletion callback.

Android: Playing two sounds one after the other

I am trying to play two sound items, one after the other
MediaPlayer mp = null;
protected void produceErrorSound(int index) {
if (mp != null) {
mp.reset();
mp.release();
}
mp = MediaPlayer.create(this, index);
mp.start();
}
public void correctAnswerAndNext(){
produceErrorSound(R.raw.right1) ;
produceErrorSound(R.raw.right1) ;
}
but only second sound is produced.
is there any alternative approach?
I can't see any wait mechanism in your code.
You can use an onCompletionListener to receive a callback when your first MediaPlayer has finished playback. At that point you can start the second MediaPlayer.
An alternative way in Jellybean (and later versions) is to use the audio chaining functionality (i.e. setNextMediaPlayer) to automatically start another MediaPlayer as soon as the current one has finished playing. Something like this (I've omitted the calls to setDataSource etc for brevity):
mediaPlayer1.prepare();
mediaPlayer2.prepare();
mediaPlayer1.start();
mediaPlayer1.setNextMediaPlayer(mediaPlayer2);

How to avoid playing 2 music files at a time in android?

I am creating an android application where I'm playing a music file from my phone. I am implementing this using services. So there is a problem in my service. When I start the service the music from my app starts playing. When I press Home Key and Went to YouTube application and played any video, The service is still running in the background paying the music file. How can I stop my service from playing the music file, when some other music file is started.
Thanks in advance.
Poll the list of running services on start of a new activity and, if it requires use of the speaker, pause yours and let it finish?
Before starting a new service, stop the running service.
When stopping the running service, make sure you stop the player too.
When the Activity or Service is starting, check whether the music is playing or not. If playing, stop it else return null as below:
I think u have the below lines in your onCreate Method of your Activity:
MediaPlayer mp= MediaPlayer.create(this, R.raw.<Your Music File>);
mp.setLooping(true);
Add the below lines of code in onPause, onStop methods in your Activity:
if(mp.isPlaying())
mp.stop();
else
return;
Create two method like this.
For audio play.
private void playAudioFile()
{
try
{
mp=new MediaPlayer();
mp.reset();
mp.setDataSource(audiofileName));
mp.prepare();
mp.start();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
and this for killMedia player.
private void killMediaPlayer()
{
if(mp != null)
{
try
{
mp.release();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
use this done it's work for me.
and call like this
killMediaPlayer();
playaudio();

Mediaplayer error (-19,0) after repeated plays

I have a game in which a sound plays when a level is completed. Everything works fine to start with but after repeating a level 10 or 20 times the logcat suddenly reports:
"MediaPlayer error (-19,0)" and/or "MediaPlayer start called in state 0" and the sounds are no longer made.
I originally had the all sounds in mp3 format but, after reading that ogg may be more reliable, I converted them all to ogg, but the errors appeared just the same.
Any idea how I can fix this problem?
I was getting the same problem, I solved it by adding the following code to release the player:
mp1 = MediaPlayer.create(sound.this, R.raw.pan1);
mp1.start();
mp1.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
};
});
I think you are not releasing the mediaplayers you are using to play the sound..
You need to release() the media players otherwise the resources are not released , and you soon get out of memory (since you allocate them again next time). so,I think you can play twice or even thrice... but not many times without releasing the resources
MediaPlayer is not a good option when you are playing small sound effects as the user can click on multiple buttons very soon and you will have to create a MP object for all of them which doesnt happen synchronously. That is why you are not hearing sounds for every click. Go for the SoundPool Class which allows you to keep smaller sounds loaded in memory and you can play them any time you want without any lag which you would feel in a mediaplayer. http://developer.android.com/reference/android/media/SoundPool.html Here is a nice tutorial : http://www.anddev.org/using_soundpool_instead_of_mediaplayer-t3115.html
I solved both the errors (-19,0) and (-38,0) , by creating a new object of MediaPlayer every time before playing and releasing it after that.
Before :
void play(int resourceID) {
if (getActivity() != null) {
//Using the same object - Problem persists
player = MediaPlayer.create(getActivity(), resourceID);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
player.release();
}
});
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
}
After:
void play(int resourceID) {
if (getActivity() != null) {
//Problem Solved
//Creating new MediaPlayer object every time and releasing it after completion
final MediaPlayer player = MediaPlayer.create(getActivity(), resourceID);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
player.release();
}
});
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
}
This is a very old question, But this came up first in my search results So other people with the same issue will probably come upon this page eventually.
Unlike what some others have said, you can in fact use MediaPlayer for small sounds without using a lot of memory. I'll put in a little modified snippit from my soundboard app to show you what I'm getting at.
private MediaPlayer mp;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
mp = new MediaPlayer();
}
private void playSound(int soundID){
mp.reset();
AssetFileDescriptor sound = getResources().openRawResourceFd(soundID);
try {
mp.setDataSource(sound.getFileDescriptor(),sound.getStartOffset(),sound.getLength());
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
}
with the way I set it up, you create on MediaPlayer object that you reuse everytime you play a sound so that you don't use up too much space.
You call .reset() instead of .release() because .release() is only used if you are disposing of an object, however you want to keep your MediaPlayer Object.
You use an assetfiledescriptor to set a new soundfile for your mediaplayer to play instead of setting a new object to your mediaplayer address because that way you are creating new objects within the method that aren't being handled properly and you will eventually run into the same error as you described.
This is only one of many ways to use MediaPlayer but I personally think it is the most efficient if you are only using it for small sound applications. The only issue with it is that it is relatively restrictive in what you can accomplish, but that shouldn't be much of an issue if you are indeed using it for small sound applications.
i try delete emulator and new create emulator for remove error of (-19,0) media player.

Categories

Resources