How to Pause/Stop MediaPlayer Android at given time programmatically? - android

I have mediaPlayer for playing sound in android and we want play files based on start time and finishing time
for example :
start 10370 ,end: 14759 [OR] start 4754 ,end: 7836
i used this code for my problem but it's not working perfect
Pause/Stop MediaPlayer Android at given time programmatically
My code :
mediaPlayer.setDataSource(fd);
mediaPlayer.prepare();
mediaPlayer.seekTo(words.getW_start());
mediaPlayer.start();
handler.postDelayed(stopPlayerTask, words.getW_end());
Do you Know why code for these times doesn't work?

I could resolve problem .complete code:
mediaPlayer.setDataSource(fd);
mediaPlayer.prepare();
mediaPlayer.seekTo(words.getW_start());
mediaPlayer.start();
new CountDownTimer(endTime, 10) {
public void onTick(long millisUntilFinished) {
if(MediaPlayerUtility.getTime(mediaPlayer)>=endTime){
mediaPlayer.stop();
}
}
public void onFinish() {
}
}.start();
and MediaPlayerUtility class:
public class MediaPlayerUtility {
public static long getTime(MediaPlayer mediaPlayer) {
long totalDuration = mediaPlayer.getDuration(); // to get total duration in milliseconds
long currentDuration = mediaPlayer.getCurrentPosition(); // to Gets the current playback position in milliseconds
return currentDuration;
}
}

Related

Play a custom sound after some time when a key pressed on android custom keyboard

I want to play a sound (custom, not system default) after some seconds when a key is pressed. I got a countdown timer running on the key. So want to play a sound onFinish function.
my code for that key is:
if(isCountDownRunning)
return;
isCountDownRunning = true;
new CountDownTimer(14000, 1000) {
public void onTick(long millisUntilFinished) {
keyboard.getKeys().get(0).label = millisUntilFinished / (1000) + "";
kv.invalidateKey(0);
}
public void onFinish() {
isCountDownRunning = false;
keyboard.getKeys().get(0).label ="ADV";
kv.invalidateKey(0);
}
}.start();
break;
You can add the custom sound in a folder res/raw/ . Then use MediaPlayer to play sound like,
MediaPlayer mMediaPlayer = MediaPlayer.create(this, rid);//rid -->R.raw.customsound
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mMediaPlayer.stop();
}
});
want to play a sound onFinish function
In your onFinish function, add this line
mMediaPlayer.start();

Play Sound OnClick Android

I simply want to play a mp3 file when I click a button in android studio.
My problem is that with the 2 methods I use the sound is played but for some reason, I hear it like an extremely distorted super slow motion sound. While if I normally open the file it is ok.
!!!!!METHOD 1:
I declared:
SoundPool mySound;
int soungId;
I initialize:
mySound = new SoundPool(1, AudioManager.STREAM_MUSIC,0);
soungId = mySound.load(this, R.raw.asd,1);
Then is use an action listener:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mySound.play(soungId,1,1,1,0,1);
}
});
!!!!!METHOD 2:
I declare:
MediaPlayer mp = null;
I use listener:
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
managerOfSound();
}
});
My managerOfSound mathod :
public void managerOfSound() {
if (mp != null) {
mp.reset();
mp.release();
}
mp = MediaPlayer.create(this, R.raw.www);
mp.reset();
mp.start();
}
It may be because the Soundpool instance of the MaxStreams maximum number (maximum number of concurrent streams) is too low
SoundPool mySound;
mySound = new SoundPool(10, AudioManager.STREAM_MUSIC,0);
try this,
MediaPlayer mp = new MediaPlayer();
// Set data source -
setDataSource("/sdcard/path_to_song");
// Play audio
mp.start();
// Pause audio
mp.pause();
// Reset mediaplayer
mp.reset();
// Get song length duration - in milliseconds
mp.getDuration();
// Get current duration - in milliseconds
mp.getCurrentDuration();
// Move song to particular second - used for Forward or Backward
mp.seekTo(positon); // position in milliseconds
// Check if song is playing or not
mp.isPlaying(); // returns true or false
http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/

E/MediaPlayer: error (1, -19)

I'm creating a simple soundboard to play sounds when a user clicks a button. Problem is, if the button is pressed enough ( usually around 10 times ) it will eventually stop playing and show the error E/MediaPlayer: error (1, -19)
what am I doing wrong? My code that plays the sound:
private void playSound(int soundID){
final MediaPlayer mp = MediaPlayer.create(this,soundID);
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mp.start();
}
});
}
You should use Soundpool. It's created exactly for playing short sound effects. And it's much simpler to use than MediaPlayer. MediaPlayer should only be used for playing regular/large music.
See here for example:
http://www.vogella.com/tutorials/AndroidMedia/article.html#tutorial-play-sounds-via-soundpool
Note: No need to use onTouch as in the example, you can just use onClick for simplicity.
Reason: "W/Choreographer: (let say) Frame time is 0.239384 ms in the future! Check that graphics HAL is generating vsync timestamps using the correct timebase."
i.e, there is a much gap between timestamps.
This problem can be removed by using setOnCompletionListener() within your OnClick() method like: `
#Overrid
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
// Get the {#link Word} object at the given position the user clicked on
Word word = words.get(position);
Log.v("NumbersActivity","Current word: "+word);
// Create and setup the {#link MediaPlayer} for the audio resource associated with the current word
MediaPlayer mMediaPlayer = MediaPlayer.create(NumbersActivity.this, word.getAudioResourceId());
// Start the audio file
mMediaPlayer.start();
// Keep timeStamp sync
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mMediaPlayer.release();
}
});
}
`
private void playSound(int soundID){
final MediaPlayer mp = MediaPlayer.create(this,soundID);
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mp.release();
}
});
}

Android: Media Player Duration Issue

I have set:
mSeekBar.setMax(mp.getDuration()); // 8480
After completion of Audiofile, What I am getting is:
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayer)
{
Log.e("onComplete>>", ""+mediaPlayer.getCurrentPosition());
// mediaPlayer.getCurrentPosition() = 8192
Log.e("getDuration", ""+mediaPlayer.getDuration());
// mediaPlayer.getDuration() = 8480
if(mediaPlayer.getCurrentPosition()>=mediaPlayer.getDuration())
{
// Why never get called???
}
}
});
So, Why is MediaPlayer's Current position never reaches the total duration of Audio file ?
Or technically we can say as:
Why Not?
mediaPlayer.getCurrentPosition()==mediaPlayer.getDuration()
Why Always
mediaPlayer.getCurrentPosition() < mediaPlayer.getDuration()
in OnCompletion listener?
For Example:
I have a Play Symbol for starting the Player. Now when I press play symbol it will convert to Pause symbol.
I have a Maxduration of audiodfile.
Now I want to convert Pause symbol to Play Symbol when Audio file is played completely.
SO what I am doing is Checking:
if(mediaPlayer.getCurrentPosition()>=mediaPlayer.getDuration())
{
// Convert Imagview from Pause to Play
// But never get called
}
If you need to do some task on completion by checking currentPoision to duration, you can do below trick:
if(mediaPlayer.getDuration()-mediaPlayer.getCurrentPosition()<1000){//milliseconds
new Handler().postDelayed(
new Runnable() {
#Override
public void run() {
// Convert Imageview from Pause to Play
}
},1000);
}

MediaPlayer.getDuration() returning wrong duration

The MediaPlayer's getDuration() method is giving me an incorrect value for some audio files. I think the common trait for all these files is that they were manipulated using Audacity or some other audio editing tool. This is a problem when trying to tie MediaPlayer progress to a Progress Bar.
I went ahead and logged it:
while(mPlayer.isPlaying())
Log.i("progress/total",
mPlayer.getCurrentPosition() +
"/" + mPlayer.getDuration());
and found this:
I/progress/total(643): 14615/14620
I/progress/total(643): 14647/14620
This is only two log line of thousands, but the point is after the progress passes what getDuration() believes to be the total duration of the song, it just keeps going. Because the MediaPlayer can in fact give the correct total for duration, is there a way to use this to get a proper maximum for my ProgressBar?
I had similar problem when MediaPlayer.getDuration() returned 542434 ms for mp3 file (HTC Desire C with ICS 4.0.3).
File itself was around 89 seconds, difference is too big.
I checked mp3 file content and saw some strange xml like:
<?xpacket begin="п»ї" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 4.2.2-c063 53.351735, 2008/07/22-18:04:26 ">
After saving this file as new one that xml was dropped and getDuration() returned correct value.
I know that it will not help those who need playing files you can't modify, but for those who can - it should help.
I was trying to play demo player a few while ago ,when i tested in Android emulator ,its behavior was the same as like you mentioned in your question but when i tried in some real device it gave me accurate value of media duration.
If your intention is only play media syncing with seekbar then you can do something like below ,
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
handler.post(new SeekbarRefresh(seekbar));
//Class to update progress of seekbar according to music player
private class SeekbarRefresh implements Runnable {
SeekBar seekBar;
public SeekbarRefresh(SeekBar seekBar, ImageView imageView) {
this.seekBar = seekBar;
}
#Override
public void run() {
if (mediaPlayer != null) {
if (mediaPlayer.getDuration() > 0) {
int currentDuration = mediaPlayer.getCurrentPosition();
seekBar.setProgress(currentDuration);
if (mediaPlayer.isPlaying()){
handler.post(this);
isAudioPlaying = true;
}
else {
handler.removeCallbacks(this);
isAudioPlaying = false;
}
}
}
}
}
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
mediaPlayer.seekTo(progress);
}
});
I have encountered a similar situation. In my case the time difference between mPlayer.getDuration() to mPlayer.getCurrentPosition() was around 80 seconds.
After reading few posts on the subject, I used third party software to convert the mp3's sample rate from 22,000 kHz to 44,100 kHz. Once converted, the result of getDuration() and getCurrentPosition() are the almost the same (0.0012s constant error).
Here is the test used:
dur = mp.getDuration();
Log.d("dur", dur + " <- getDuration");
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// finish current activity
Log.d("dur", mp.getCurrentPosition() + " <- getCurrentPostion");
}
});

Categories

Resources