Back to back Small MP3 files Playing In Android - android

I want to play back to back mp3 files(of half sec) in my android application.I am able to do that on emulator but on mobile phone they all are overlapping with each other.
I have used OnCompletionListerner and stopped the Mediaplayer.
Following is my code for one mp3 file:
mPlayer = MediaPlayer.create(MainActivity.this, R.raw.a10);
mPlayer.start();
mPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mPlayer) {
// TODO Auto-generated method stub
mPlayer.stop();
}
});
Can anybody suggest any method to stop the overlapping?

Try following example :
MediaPlayer mp1, mp2;
Timer timer;
// Create two different instances of mediaplayer
mp1 = MediaPlayer.create(MainActivity.this, R.raw.a1);
mp2 = MediaPlayer.create(MainActivity.this, R.raw.a2);
// Create the timertask
timer = new Timer("mytimer");
timer.schedule(timertask1, 1000);
onCompletionListeners:
// Completion listener for Audio file 1.
mp1.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(final MediaPlayer cim) {
//On completion of first audio, release the resources of mediaplayer
mp1.release();
mp1 = null;// free up memory
// Start the timertask of 2nd audio file
timer = new Timer("mytimer");
timer.schedule(timertask2, 1000);
}
});
mp2.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(final MediaPlayer cim) {
//On completion of 2nd audio, release the resources of mediaplayer
mp2.release();
mp2 = null;
// Start the timertask of 1st audio file or nxt audio file if you want to play file or simplly you can stop here.
timer = new Timer("mytimer");
timer.schedule(timertask1, 1000);
}
});
Timer tasks:
private TimerTask timertask1 = new TimerTask() {
#Override
public void run() {
mp1.start();
}
};
private TimerTask timertask2 = new TimerTask() {
#Override
public void run() {
mp2.start();
}
};
Note:
Example is given considering two audio files only, hence two specific onCompletionlisteners and timertasks. However I would suggest you to use generalised code for creating the mediaplayer instance, onCompletionlistener and timertask.

Related

Android Media player onClick issue

I'm using MediaPlayer for playing sounds onClick. Until the sound is finished the click event is not play the sound again. How can it play the sound again on click, when the sound is currently playing?
final MediaPlayer mistake = MediaPlayer.create(getActivity(), R.raw.mistake);
tv_mistake.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mistake.start();
}
});
You must create a new MediaPlayer object to play the sound again like so.
tv_mistake.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mistake != null) {
mistake.release();
mistake = MediaPlayer.create(getActivity(), R.raw.mistake);
}
mistake.start();
}
});
You can read more about MediaPlayer in the following links.
Also a quite similar question
MediaPlayer, MediaPlayer Tutorial, MediaPlayer Tutorial From Google
Most of the errors in MediaPlayer comes due to improper handling of different states of its object.
You should release MediaPlayer object after completing playback or before calling start() again.
It is also recommended that once a MediaPlayer object is no longer being used, call release() immediately so that resources used by the internal player engine associated with the MediaPlayer object can be released immediately.
Create a MediaPlayer object as:
Mediaplayer mediaPlayer = null;
And call playMistakeSound() on button click:
tv_mistake.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playMistakeSound()
}
});
Implement playMistakeSound() as:
void playMistakeSound() {
try {
// releases MediaPlayer object before calling create() again while previous is still playing
if (mediaPlayer != null){
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}
mediaPlayer = MediaPlayer.create(getActivity() /*Context*/, R.raw.mistake);
// this will release MediaPlayer as soon as it completes
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if (mp != null) {
mp.reset();
mp.release();
mediaPlayer = null;
}
}
});
mediaPlayer.start();
} catch (Exception e) {
// log exception and handle
e.printStackTrace();
}
}

Play sound sequentially with no delay between the parts [Android]

In my Android application I want to play sequentially some sound that was divided to parts before. Each part is a .wave file with 2-3 seconds length.
I do perform that successfully, but I have a noticeable delay between those parts.
My code looks now like that -
localMediaPlayer = new MediaPlayer[3];
localMediaPlayer[0] = MediaPlayer.create(this, R.raw.sound_1);
localMediaPlayer[1] = MediaPlayer.create(this, R.raw.sound_2);
localMediaPlayer[2] = MediaPlayer.create(this, R.raw.sound_3);
public void onClick_localBtn(View v){
Toast.makeText(this, "Play Local Sound", Toast.LENGTH_LONG).show();
localMediaPlayer[0].start();
localMediaPlayer[0].setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
public void onCompletion(MediaPlayer mp) {
localMediaPlayer[1].start();
}
});
localMediaPlayer[1].setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
public void onCompletion(MediaPlayer mp) {
localMediaPlayer[2].start();
}
});
}
How can I improve my code that those parts will play smooth and with no delay, like if it were a 1 file sound?
Thanks.
When you start playing your (N)th media player, call prepareAsync() on your (N+1)th media player:
localMediaPlayer[0].start();
localMediaPlayer[1].prepareAsync();
localMediaPlayer[0].setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
public void onCompletion(MediaPlayer mp) {
localMediaPlayer[1].start();
localMediaPlayer[2].prepareAsync();
}
});
localMediaPlayer[1].setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
public void onCompletion(MediaPlayer mp) {
localMediaPlayer[2].start();
}
});
Edit
Based on your update and your comment, perhaps a better way would to be time the playing of the next media player according to the duration of the previous player minus some delta:
private static final int DURATION_DELTA = 1000;
private Handler mHandler = new Handler();
public void playMediaPlayer(final int index) {
if (index >= localMediaPlayer.length || localMediaPlayer[index] == null)
return;
localMediaPlayer[index].start();
final int duration = localMediaPlayer[index].getDuration();
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
playMediaPlayer(index + 1);
}
}, duration - DURATION_DELTA);
}
This code will basically play a media player, then schedule playing the next media player approx 1 second before the next media player ends. It's a bit "hacky", but you can play around with it (the value for DURATION_DELTA) until you get the best results.

Android How to delete MediaPlayer perfectly

I am trying to develop a simple test project that plays sound when I tap the button and stop automatically after a few minutes after playing the sound.
Here is a code snippet:
Code for playing:
if (mPlayer != null) mPlayer = null;
mPlayer = MediaPlayer.create(this, R.raw.shush_v2);
mPlayer.setLooping(true);
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
Code for stopping:
if(mPlayer != null && mPlayer.isPlaying()) {
mPlayer.stop();
mPlayer.reset();
mPlayer.release();
mPlayer = null;
}
But sometimes I can still hear two sounds playing after I've stopped the sound.
Have so ever seen this behaviour before?
You should clear your media player.
//example usage of clearing media player when its over.
ourSong.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
clearMediaPlayer(mp);
}
});
//You can use this to stop media player.
private void clearMediaPlayer(MediaPlayer mp){
if(mp!=null){
mp.stop();
mp.release();// this will clear memory
mp = null;
}
}
public class PlayerApp extends Activity {
Button btnStart;
MediaPlayer mediaPlayer = null;
// Use the handler to stop the Player, after specific time
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player_app);
btnStart = (Button)findViewById(R.id.btnStart);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
// Initialize Player and start it.
// Call the Handler same time.
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.test);
mediaPlayer.start();
startHandler();
}
});
}
private void startHandler()
{
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// if Player is not null, then Stop it and Reset Null.
if(mediaPlayer!=null)
{
mediaPlayer.stop();
mediaPlayer = null;
}
}
}, 2500);
}
}

Android Studio- Media Player doesn't play sound On Genymotion?

I am trying to build a small app which plays a sound when we click on the button. But I am not able to play the sound. Don't know what the problem is. Please help me on this. Below is the code.
public class MainActivity extends AppCompatActivity {
private Button button;
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.song);
button = (Button)findViewById(R.id.mediaButtonId);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.start();
}
});
}
}
Note:-Sorry guys,I thought that the problem is with my code but the app is running perfectly fine on my phone,so its the problem with my genymotion emulator.Can anyone please suggest me the solution for this.By the way,I am using Mac OSX.
The MediaPlayer has its own lifecycle. You can't just create the instance and then start to play. First you have to prepare it and then play it.
You can prepare your mediaplayer either sync or asynchronously.
Something along the lines of:
MediaPlayer mediaPlayer= new MediaPlayer();
mediaPlayer=MediaPlayer.create(getApplicationContext(),R.raw.song);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
Or, if you want to do it synchronously
MediaPlayer mediaPlayer= new MediaPlayer();
mediaPlayer=MediaPlayer.create(getApplicationContext(),R.raw.song);
try {
mediaPlayer.prepare();
} catch (IOException e){
}
mediaPlayer.start();
Just make sure you prepare it before you play it.
Media Player lifecycle: https://developer.android.com/reference/android/media/MediaPlayer.html
You need to make sure the media player is ready before you can play it, so you set the onPreparedListener to handle this for you, like so:
MediaPlayer mp = new MediaPlayer();
mp = MediaPlayer.create(getApplicationContext(),R.raw.song);
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mp.start();
}
});
button = (Button)findViewById(R.id.mediaButtonId);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.prepareAsync();
}
});
There will be a slight delay from when you press the button to the sound playing this way. Another way to do it could be to disable the button until the media player has prepared and then in the onclick of the button you could just call mp.start(); when the button has been enabled.

How to play audio user define times in android?

Can anyone give me a link of function to play audio file using user define time.. I am using handler but something is missing..
I am also done infinite time audio play but we need user defined times audio play.. Thanks...
Infinite time play audio is done using below function..
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shri_krushna_fast);
// mMediaPlayer.setVolume(0.2f, 0.2f);
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer arg0) {
mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shri_krushna_fast);
mMediaPlayer.start();
}
});
mMediaPlayer.setLooping(true);
mMediaPlayer.start();
}
I just wanted how to play audio x times in android using Thread??
I am updating my function but i was not got 100% on this..so plz help
my updated function is as bellow
public void Repeat_mantra()
{
mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shri_krushna_fast);
// mMediaPlayer.setVolume(0.2f, 0.2f);
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer arg0) {
mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shri_krushna_fast);
for(count=1;count<5;count++)
{
mMediaPlayer.start();
while(mMediaPlayer.isPlaying());
}
}
});
// mMediaPlayer.setLooping(true);
mMediaPlayer.start();
}
But this function is running then other clicks/or user interface are not appear because of "while(mMediaPlayer.isPlaying());" so any help me for how to update my function with Thread??

Categories

Resources