Mediaplayer gap before playing another - java

I have a few media players setup to play one after another on a button click however there is a noticeable gap between the media players playing ie. once mediaplayer one has finished there is a half a second before mediaplayer two plays, for the purpose I'm using the mediaplayers for the gap in audio is very noticeable, so what I'm asking is, is there a way to remove this gap. Now I don't know if I'm going wrong using different mediaplayers each time however this is what I've come up with so far.
Basically I've got onCompleteionListeners for each mediaplayer and within those I have the next mediaplayer play until the last. Any pointers would be appreciated.
public void onClick(View v) {
mpButtonThree = MediaPlayer.create(MainActivity.this, R.raw.audioReplay);
if (mpButtonThree==null){
//display a Toast message here
return;
}
mpButtonThree.start();
mpButtonThree.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mpButtonThree) {
mpButtonThree.release();
mpButtonOne = MediaPlayer.create(MainActivity.this, audioReplayPrimary);
if (mpButtonOne==null){
//display a Toast message here
return;
}
mpButtonOne.start();
mpButtonOne.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mpButtonOne) {
mpButtonOne.release();
mpButtonTwo = MediaPlayer.create(MainActivity.this, audioReplaySecondary);
if (mpButtonTwo==null){
//display a Toast message here
return;
}
mpButtonTwo.start();
mpButtonTwo.setOnCompletionListener(new soundListener1()
{
});
}

If You play files in series you can use single media player object.
create function that plays next media file and put it into OnCompletion.
This should remove gap between playing, because You don't have to release and create media player every time

Related

Android studio check if Mediaplayer is playing in a screen widget activity

There'd be a button on the home screen which would play a certain song and change the background image of the button. If the user clicks on the button again (when the music is playing) then the music should stop and the background image of the button should set itself back to the general position. But it looks like the program can't detect if my Mediaplayer is playing. What am I missing here?
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
AppWidgetManager appWidgetManager= AppWidgetManager.getInstance(context);
RemoteViews rv= new RemoteViews(context.getPackageName(),
R.layout.playbtn_widget);
if (intent.getAction().equals("btnPlay")) {
if (!mediaPlayer.isPlaying()) {
mediaPlayer= MediaPlayer.create(context,R.raw.itsmylife);
mediaPlayer.start();
rv.setImageViewResource(R.id.imbtnwidget,
R.drawable.btnk32);
} else {
mediaPlayer.stop();
}
mediaPlayer.setOnCompletionListener(mediaPlayer -> {
rv.setImageViewResource(R.id.imbtnwidget,
R.drawable.btnk3);
appWidgetManager.updateAppWidget(new ComponentName(context,
BtnAppWidgetProvider.class), rv);
});
appWidgetManager.updateAppWidget(new ComponentName(context,
BtnAppWidgetProvider.class), rv);
}
}
It should set the background image back and stop the music when I tap on the button, but it just starts the mediaplayer again and the background image remains the same. I have no idea how I could fix this. It seems like it creates a new mediaplayer every single time
Issue
It creates a new Media Player because the class is recreated or re-executed. This clears all the variables and re-defines them. This makes the issue in your case.
Solution
Just create a class name anything like MediaPlayerHelper.java
Create a variable of MediaPlayer which is public and static. Like this:
public static MediaPlayer mp;
Now, when the button is pressed, you can check if it is playing or not. Something like this:
if(MediaPlayerHelper.mp != null && MediaPlayerHelper.mp.isPlaying()){
// the media player is currently playing. Stop it.
}else{
// the media is not playing. Start it
}

Playing songs one after another in Android(Java)

I want to play songs one after another in my music player app. I checked this question but my music player plays the next song only once. After that it stops. For example, it's playing Song A, then it'll play next Song B, but after song B it won't play Song C.
Here is my code:
OnCompleteListener:
//mp is MediaPlayer object, al is ArrayList of songs and their ids(R.raw.song), song_no is the index of the song in al
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
song_no = (song_no +1) % al.size();
playSong();
}
});
I have the same code for "next" button which works perfectly, even after reaching the end of list it loops back.
playSong function:
public void playSong()
{
song = Uri.parse("android.resource://" + getPackageName() + "/" + al.get(song_no).id());
try
{
mp.stop();
mp.reset();
mp.release();
mp = null;
}
catch(Exception e)
{
Log.d("playSong", e.toString();
}
mp = MediaPlayer.create(getApplicationContext(), song);
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
I tried removing mp.reset(), mp.release() and mp = null but it still played the next song only once.
It looks like you want a Queue data structure, hopefully is gonna be easier to handle than keeping track of indexes.
Your al variable would store a queue of songs to play, in your onCompletion method you can call a playNextSong() method that handles the queue using poll() or remove() to get the next song and play until the queue is empty.
If you want to keep your ArrayList, Try debugging your song_no and song variables to narrow down if the problem is in the song order logic or the MediaPlayer usage.

Is there a way to play different audio files without calling them each with their own function?

I have 8 audio files that I need to play when a button is pressed.
Currently, these files are played using a class. In this class, each audio file has it's own function that plays and pauses each audio file.
Is there a way to do this without repeating the same function for different audio files?
The button in question is connected to an Adafruit feather - essentially if the button is pressed the phone knows to play whichever audio is required.
Here's some code:
Here's what I have so far:
public class Audio {
MediaPlayer mp;
boolean paused = false;
public void playSound_1(Context context) {
mp = MediaPlayer.create(context, R.raw.Sound_1);
mp.start();
}
public void playSound_2(Context context) {
mp = MediaPlayer.create(context, R.raw.Sound_2);
mp.start();
}
public void playSound_3(Context context) {
mp = MediaPlayer.create(context, R.raw.Sound_3);
mp.start();
}
}
In my fragment I then call the function for each sound:
if (data_check.contains("Sound_1"){
audio.playSound_1(this.getContext());
}
else if (data_check.contains("Sound_2"){
audio.playSound_2(this.getContext());
}
The current results are that if the button is pressed (and data_check finds the name of the Sound) that sound plays.
What I'd like to do is have the same results but without having public void playSound_1, 2, 3, 4... etc.

Playing a sound on android

I have come across another error along my first app journey :) I want to play a sound when the app loads. Which is a .wav file. It lasts 2 seconds long yet it does not play when I run the app on my old Samsung S4. There is no errors within the IDE or anything I can see, I have checked if 'mp' has a value and it does. Looking around on posts most people have the problem that 'mp' is = null. Whereas mine has a value just no sound comes out of the phone... Again, any help is appreciated!
public class OpeningScreen extends Activity {
#Override
// create the screen state
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// connect the xml layout file
setContentView(R.layout.activity_opening_screen);
final MediaPlayer mp = new MediaPlayer();
mp.create(this, R.raw.welcome_message);
mp.start();
// create the on touch listener
ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.opening_layout);
layout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// change the screen to a new state
Intent intent = new Intent(OpeningScreen.this, GameScreen.class);
// start the new activity
startActivity(intent);
// stop welcome sound (if still playing)
mp.stop();
return true;
}
});
}
}
public static MediaPlayer create(Context context, int resid) is a static method to create a MediaPlayer for a given resource id.
It means that by calling create you are creating a new instance of media player with no reference usage.
Try to change
final MediaPlayer mp = new MediaPlayer();
mp.create(this, R.raw.welcome_message);
to
final MediaPlayer mp = MediaPlayer.create(this, R.raw. welcome_message);
And the player should work.
It's better to register for OnPreapredListener via MediaPlayer.setOnPreaparedListener and after preparation you start your media playback.
http://developer.android.com/guide/topics/media/mediaplayer.html
Why do you use final?
You can play a mp3 with
MediaPlayer mp = MediaPlayer.create(OpeningScreen.this, R.raw.welcome_message);
mp.start();
Also stopping mediaplayer is better if you stop in onDestroy.
public void onDestroy() {
mp.stop();
super.onDestroy();
}

How can I use Intent on Java, Android?

I have written the following code for playing video:
private void loadPlayer() {
Intent youtube=new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=CES7xNy70hU"));
startActivityForResult(youtube, 100);
}
My problem is that when the player finishes showing the video it won't close itself and the user needs to press the back button. I need the player to close itself automatically after the video has finished playing. How can I accomplish this?
The target platform is Android - 2.2.
Create an activity that just displays a VideoViewer. Play the video from there. Implement a listener for the completion of the video. Then call finish within there to end the activity:
videoViewer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp)
{
finish();
}
});
This will return you to the previous Activity.

Categories

Resources