I am trying to play next song with mediaPlayer.setOnCompletionListener() but it only plays one next song and after that song ends mediaplayer stops.How to make mediaplayer play all the time?
Intent i = getIntent();
Bundle b = i.getExtras();
mySongs = (ArrayList)b.getParcelableArrayList("songList");
position = b.getInt("pos",0);
u = Uri.parse(mySongs.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(), u);
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.stop();
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
u = Uri.parse(mySongs.get(position + 1).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(), u);
mediaPlayer.start();
}
});
You don't need to wait until onCompletion. Just create both players at once and use setNextMediaPlayer to queue the second one
u1 = Uri.parse(mySongs.get(position).toString());
u2 = Uri.parse(mySongs.get(position + 1).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(), u1);
mediaPlayerNext = MediaPlayer.create(getApplicationContext(), u2);
mediaPlayer.setNextMediaPlayer(mediaPlayerNext);
And you are not receiving onCompletion after the second song because you replace mediaPlayer value with a reference to a new player that doesn't have the listener set. Add mediaPlayer.setOnCompletionListener() to the onCompletion handler. You also don't need to prepare old player
Related
I set a music file to loop on MediaPlayer for my game, but it causes a 2 sec delay when it loops.
My code:
boolean activateSounds = getIntent().getBooleanExtra("Activate sounds", true);
if(mp!=null){
mp.reset();
mp.release();
}
mp = MediaPlayer.create(StartGame.this, R.raw.music1);
mp.setVolume(8f, 8f);
mp.setLooping(true); // This is causing delays
if (activateSounds) mp.start();
For a game, this is not interesting. Is there a way to make MediaPlayer run out of loop delays?
I was not able to make setLooping work without a gap.
Only solution that worked for me was to use setNextMediaPlayer call (which is able to start next loop without a gap) and two MediaPlayers.
'pseudo' code:
class Abc implements MediaPlayer.OnCompletionListener {
private final MediaPlayer[] mps = new MediaPlayer[2];
public Abc() {
mps[0] = new MediaPlayer();
mps[1] = new MediaPlayer();
mps[0].setOnCompletionListener(this);
mps[1].setOnCompletionListener(this);
}
public void start()
initMediaPlayer(mps[0]);
initMediaPlayer(mps[1]);
mps[0].setNextMediaPlayer(mps[1]);
mps[0].start();
}
private void initMediaPlayer(MediaPlayer mp)
{
if (mp.isPlaying()){
mp.stop();
}
mp.reset();
final float volume = 0.07f;
mp.setDataSource(MY_SOURCE);
mp.setVolume(volume, volume);
mp.setLooping(false);
try {
mp.prepare();
}catch(Exception error){
Log.d("BackgroundMusic", error.toString());
}
}
#Override
public void onCompletion(MediaPlayer mp)
{
MediaPlayer cur = mps[0] == mp ? mps[1] : mps[0];
initMediaPlayer(mp);
cur.setNextMediaPlayer(mp);
}
}
when I play a sound file the sounds stops after a second. How can I make sure the sound keeps playing?
final Button BtPlaySound = (Button) resultdialog.findViewById(R.id.BtPlaySound);
BtPlaySound.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
//play sound
/*final MediaPlayer player = MediaPlayer.create(ActivityMain.this, R.raw.r);
player.setLooping(true); // Set looping
player.setVolume(100,100);
player.start();
*/
Context context = ActivityMain.this;
MediaPlayer mp = MediaPlayer.create(context, R.raw.r);
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.r);
}
mp.start();
} catch(Exception e) {
e.printStackTrace();
}
//End Of PlaySoundFunction
}
I have a application in which when i select any item then it will play that media file but when i select other item then the old media is playing continue and the current media file is overlay(current file is also playing) so i am listen both media files.
I have written below code:
ImageView songView;
Gallery songGallery;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.song_test);
songView = (ImageView) findViewById(R.id.songView);
songGallery = (Gallery) findViewById(R.id.songGallery);
songGallery.setAdapter(new MyGalleryAdapter(getApplicationContext()));
songGallery.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View arg1,
int arg2, long id) {
// TODO Auto-generated method stub
songView.setImageResource(symbolIds[arg2]);
String imageName = getResources().getResourceEntryName(
symbolIds[arg2]);
Uri audio = Uri.parse("android.resource://" + getPackageName()
+ "/raw/" + imageName + "");
mp = MediaPlayer.create(getApplicationContext(), audio);
try {
if (mp.isPlaying()) {
mp.reset();
}
mp.start();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Error", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
....
....
}
}
So my question is - When i select the item the song is playing very well but when i select other item then the old song is also playing with the current.
so i want to stop the old song...
I want to play only current selected item song.
The issue is that MediaPlayer is being recreated instead of being reset. Rather than using the #create() factory call, you can use the constructor instead. In the following code, if the mp is already created it is reset and then a datasource is prepared and started.
if (mp != null) {
mp.reset();
} else {
mp = new MediaPlayer();
}
// Now set the datasource
mp.setDataSource(context, audio);
mp...
mp.prepare();
mp.start();
Ideally though you should call prepareAsync and have a callback onPrepare() call the actual mediaPlayer.start so that prepare does not block the main thread.
mp.setOnPreparedListener(this);
mp.setDataSource(..)
mp.prepareAsync();
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
Make the MediaPlayer mp global variable private static. Better yet use Singleton instead of global
You could review the state diagram here
then review an implementation of that logic for recycle media player in the
media sample you can find in your SDK installation:
$SDK/.../src/com/android/sample/apis/media/MediaPlayerDemo_Video.java
and follow how the sample resets the player state before using it again
I'm having an issue with some android code to play a sound notification on certain events.
Here's the code:
int result = audioManager.requestAudioFocus(MainRunningService.afChangeListener,AudioManager.STREAM_NOTIFICATION,AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
mp = new MediaPlayer();
mp.setDataSource(context, soundToPlay);
mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
mp.prepare();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayer) {
try {
Log.d(LOGTAG, "SoundService MUSIC: MUSIC IS NOW COMPLETE");
mp.release();
mp = null;
Log.d(LOGTAG, "SoundService MUSIC: MUSIC IS NOW COMPLETE - RELEASED");
} catch (Exception e) {
e.printStackTrace();
}
}
});
mp.setLooping(false);
mp.start();
}
else{
Log.w(LOGTAG, "SoundService Audiofocus was not granted");
}
What I'm finding is that sometimes it will play, whereas other times it won't play. When it doesn't play it's hitting the "SoundSerice Audiofocus was not granted" log line. I've looked at the system logs, but can't find anything that says why it's not been granted.
Once this has happened, then every request seems to fail.
Does anyone have any pointers to what I might be doing wrong?
//call the method playAssistClip() on button click or wherever you want.
private MediaPlayer mp;
private void playAssistClip() {
if (workoutReps.equalsIgnoreCase("6x6x6")) {
mp = MediaPlayer.create(ProcessWorkout.this,
R.raw.six_six_six_formated_ogg);
mp.setOnCompletionListener(new OnCompletionListener() {
//do something after the audi ends
mp.reset();
mp.release();
finish();
}
});
mp.start();
//to get the duration of clip
spentTimeOnWorkout = mp.getDuration();
}
i am playing mp3 sound using default media player of android, my code for plying sound below
MediaPlayer mp=MediaPlayer.create(hello.this,R.raw.abc);
if(mp!=null)
{
mp.start();
}
i need to play same sound on same button click. when i click continuously on button after some time sound is not working and i getting error MediaPlayer(7395): error (-19, 0).
Does any body have idea for this issue,
Please send me
Thank in advance.
call
mp.reset();
because ever time you are decalaring object
or declare on class level Mediaplayer OBject
Make global variable of mediaplayer and try this way
MediaPlayer mp;
if (mp!=null) {
mp.stop();
mp.release();
}
mp= MediaPlayer.create(hello.this,R.raw.abc);
mp.start();
mp = new MediaPlayer();
mp.create(this, R.raw.testmed);
mp.setVolume(100, 100);
mp.setOnPreparedListener(this);
mp.prepare();
Then you will need to define this and it should work:
public void onPrepared(MediaPlayer player) {
mp.start();
}
you can play music like below
// for play the song
MediaPlayer mp = new MediaPlayer();
try
{
mp.reset();
mp.setDataSource(songPath);
mp.prepare();
mp.start();
btnPlay.setBackgroundResource(R.drawable.img_btn_pause);
} catch (IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
I have found solution for this issue. i have correct this issue using below code, May help other also.
Thanks
Call Method like
PlaySound(R.raw.abc);
//Method
private void PlaySound(int Sound_id)
{
mplayer = MediaPlayer.create(Act_Oceanwaves.this,Sound_id);
if(mplayer!=null)
{
mplayer.start();
}
mplayer.setOnCompletionListener(new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
mp.release();
}
});
}