Android MediaPlayer or SoundPool? - android

When I use mediaplayer on click button, after several clicks the sound disappears. When I use soundpool, the time is too short to play the effect sound. Can anybody please help me with this?

As I understood your audio is 20 s. So you can use this code on your button click:
if (mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
mediaPlayer = MediaPlayer.create(this, R.raw.audio_file);
mediaPlayer.start();
The first if statement is to take care that it will keep playing how much ever you clicked the button.

Related

MediaPlayer main thread android

I was using SoundPoolto play sound effects but now I need to switch to MediaPlayer as I need to listen to the onCompletion event to trigger a GUI change.
My questions are:
The sound files are very small, less than 30kB, Can I use
MediaPlayer in the main thread?
Can I just call mediaPlayer.stop() after the play is done like so,
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayer) {
//Do some GUI changes
mediaPlayer.stop();
mediaPlayer.release();
}
});
Then to play another effect will do this:
mediaPlayer = MediaPlayer.create(context, R.raw.sound_file_1);
mediaPlayer.start();
So, is it ok to create and release every time I play an effect?
Initialize your MediaPlayer
MediaPlayer mediaPlayer = new MediaPlayer();
AssetFileDescriptor afd = context.getResources().openRawResourceFd(resid);
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
Look at the MediaPlayer lifecycle:
When the track is complete the MediaPlayer is in Stopped state and you wan't to change the track, so:
call reset()' to get toIdlethensetDataSourcethenprepareand finallystart()`.
The sound files are very small, less than 30kB, Can I use MediaPlayer in the main thread?
Irrespective of the size of your audio file, you should run MediaPlayer on its own thread, especially if you are playing a file from network. Not doing so may cause ANR (In your case I don't think much to worry about)
Can I just call mediaPlayer.stop() after the play is done
There is no need to release the MediaPlayer after every audio file. Release it once you are no longer going to use it.
how can I load a new sound
AssetFileDescriptor audio = context.getResources().openRawResourceFd(R.raw.next_audio);
mediaPlayer.setDataSource(audio);

Play sound precisely every one second

I am learning to code for Android and I have a problem with... maybe performance?
I want to play very short sound every second. I have created a CountDownTimer (with tick interval 20ms so very accurate) and putted there in onTick to play it. But the sound is played not precisely after one second and I can hear this - this is the problem...
fragment of my code:
private class ExerciseCountDownTimer extends CountDownTimer
{
...
public void onTick(long millisUntilFinished)
{
...
if(/*this is a next second not just a tick*/)
playSound(R.raw.quick_rest, true);
}
}
private void playSound(int resId, boolean releaseAfter)
{
if (currentMediaPlayerRes != resId || mediaPlayer == null)
{
if (mediaPlayer != null)
{
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
}
currentMediaPlayerRes = resId;
mediaPlayer = MediaPlayer.create(this, resId);
if (releaseAfter)
{
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
mediaPlayer.release();
mediaPlayer = null;
}
});
}
}
mediaPlayer.start();
}
Is it possible to have counter like this?
use this code to play a music one time
MediaPlayer AlarmMusic;
AlarmMusic = MediaPlayer.create(G.context, R.raw.music1);
AlarmMusic.setLooping(false);
AlarmMusic.start();
this worked for me !
Because of the lack of real time guarantees in Java/Android, using one thread to cue another probably will always have some inaccuracy.
I can think of two approaches that might work for you:
(1) make the sound file exactly 1 second long, e.g., 44100 frames at 44100 fps, if you are using the standard "CD-quality" format that Java supports. The sound file can probably be edited with Audacity to an exact frame length. Then, use a looping playback.
(2) Open a line for streaming audio. I can't recall exactly what the Android-supported command is for this, but I know it exists. With it, count elapsing frames while sending silence (bytes with 0 value). When you get to the 44100th frame, start feeding the PCM data that you wish to hear. When it is done, go back to feeding 0's until the next 44100 frame arrives. Never stop the line--keep it running in its own thread, probably with a high priority. It is generally okay to give audio a high priority (as long as you are doing nothing else on the line) as audio spends a vast majority of its time in a "blocked" state during which it is yielding to other lines.
A fellow on java-gaming.org made a metronome and got it working on Android. I bet if you search for "metronome" on that site, his thread will pop up and have some useful info. He basically used the second approach that I described above.

Android MediaPlayer getCurrentPosition returns 0

I am using a MediaPlayer to play several audio files. I have a custom MediaController based on androids MediaController. The problem I am having is that when I pause the player the controller shows the current position as 0 until I hit play again. I have traced it down to the media player returning 0 as its position while paused. Is this the intended behavior?
Thanks,
Nathan
A simple fix would be put up a static int that catches the currentposition of the media player before it is stopped or paused.
int currentPos = mediaPlayer.CurrentPosition;
mediaPlayer.Stop();
mediaPlayer.Release();
stopIsActive = true;
WriteSeekingToDataBase(currentPos, CurrentSongObject);

play 3 audio files one after the other

I have an array of audio files and I want to play 3 audio files one after the other, so as the gap in between them is not noticeable.
I am trying it using onCompletion listener but unable to do.
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
// TODO Auto-generated method stub
if ((image100==1)&&(image10==0)&&(image1==1))
{
mediaplayer = MediaPlayer.create(getApplicationContext(), sounds[0]);
mediaplayer.start();
mediaplayer = MediaPlayer.create(getApplicationContext(), sounds[12]);
mediaplayer.start();
mediaplayer = MediaPlayer.create(getApplicationContext(), sounds[3]);
mediaplayer.start();
}
}
You may want to try using the AudioTrack class to play your sounds. With it, you can get very close and even overlapping sounds. To use it, you create separate threads for each sound.
Here's the AudioTrack reference page and here's an easy to follow blog entry where the author implements a piano with arbitrary length and simultaneous sounds. In it, he loops very short duration sounds, but you could easily adapt that to longer, single-play sounds.
If these 3 audio files are short sounds, like game sound effects or piano tones, you can use SoundPool for playing them.
Here is a link to the sample code:
Game Sound effects in Android

Media Player replay button

I am making an app that involves sound. There is a replay button. All I want is, whenever that is hit, my song whenever finished or in play, to be played from the beginning. I have tried many thing like
mp.stop();
mp.start();
or
mp.stop();
mp.prepare();
mp.start();
but none of them worked. Can you help me?
try to seek player to 0 before you stop it:
mp.seekTo(0);
mp.stop();
mp.start();

Categories

Resources