How can I make android mediaplayer play sound? - java

I don't know why it doesn't works, there is no error logged in logcat, but I cannot hear a sound.
public static void DeclararSonido(int numero, Context contexto){
switch(numero){
case 0:
mp = MediaPlayer.create(contexto, R.raw.alan);
break;
}
}
public static void TocarPiedra( int posicion, Context contexto){
DeclararSonido(posicion, contexto);
mp.start();
mp.stop();
mp.release();
}
public static void TocarSirena(Context contexto){
MediaPlayer mp2= MediaPlayer.create(contexto, R.raw.doh);
mp2.start();
mp2.stop();
mp2.release();
}
If I erase mp2.stop(); and mp2.release(); AND mp.stop(); and mp.release(); the app plays the sound, but the file is not released...

You certainly do not want to Start and then Stop right away..
The problem is that you are executing these right after each other:
mp.start(); // starts playback
mp.stop(); // .. then stops immediately ..
mp.release();
You should call start, and then when the sound is done playing, release. You can use the Completion event to hook up a listener and release there:
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
public void onCompletion(MediaPlayer player) {
player.release();
}
})

Mediaplayer.create():- creates the new object of mediaplayer .this object is having music file from raw folder which is to be played when start() method is called
Mediaplayer.start():- *starts playing music* if object Mediaplayer is initialized .otherwise gives exception.
Mediaplayer.stop() :-*stops* the current ongoing music with that object.
Mediaplayer.release():-the music file path is no longer associated with Mediaplayer object. so u need to reallocate memory and all. mind it mediaplayer would not be null .
go here and see the state diagram of mediaplayer
Now what you are doing is that starting the song and directly stopping it .I would suggest you to create button , and when button is pressed stop the mediaplayer.
Other way is already given by Miky Dinescu that setoncompletelistner.
so, do as follows
public static void DeclararSonido(int numero, Context contexto){
switch(numero){
case 0:
mp = MediaPlayer.create(contexto, R.raw.alan);
break;
}
}
public static void TocarPiedra( int posicion, Context contexto){
DeclararSonido(posicion, contexto);
mp.start();
mp.setOnCompleteListener(new OnCompleteListener(){
public void OnCompletion(MediaPlayer mp){
mp.stop();
mp.release();
}});
}
public static void TocarSirena(Context contexto){
MediaPlayer mp2= MediaPlayer.create(contexto, R.raw.doh);
//Alomejor es por la extension
mp2.start();
mp2.setOnCompleteListener(new OnCompleteListener(){
public void OnCompletion(MediaPlayer mp){
mp2.stop();
mp2.release();
}});
}

Related

I have a problem with Media Player when playing the audio, it does not stop even when I exit the application How do I release this code?

enter code here
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
btPause.setVisibility(View.GONE);
btPlay.setVisibility(View.VISIBLE);
mediaPlayer.seekTo(0);
}
});
}
#SuppressLint("DefaultLocale")
private String convertFormat(int duration) {
return String.format("%02d:%02d"
, TimeUnit.MILLISECONDS.toMinutes(duration)
,TimeUnit.MILLISECONDS.toSeconds(duration) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration)));
}
}
enter code here
I think you are creating a Mediaplayer instance everytime. Make sure that instead of the instantiation is
MediaPlayer mp;// above the onCreate section
mp=MediaPlayer.create(this, R.raw.animal_kit);
instead of
MediaPlayer mp=MediaPlayer.create(this, R.raw.animal_kit);

My android App stop playing sound on button tap after some time

Hello there, i have just created a basic android app which plays different musics on button tap..
The app just worked fine for the first couple of seconds but when i just keep on tapping and tapping , at some point it stops playing the music and just crashed...
I am unable to figure out what the problem is ..Please help me make it work..
Thanks.
Here is my code :-
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
public void PlayMusic(View view)
{
int ID = view.getId();
String NameID = view.getResources().getResourceEntryName(ID);
int sound= getResources().getIdentifier(NameID,"raw","com.example.pickachu.mypatatap");
mediaPlayer = MediaPlayer.create(this,sound);
mediaPlayer.start();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
The sound is not playing after multiple taps because you must be getting IllegalStateException because you are not releasing the Mediaplayer object and Mediaplayer Lifecycles are not managed properly when you tap multiple times.
You can use setOnCompletionListener(MediaPlayer.OnCompletionListener listener) to release mediaPlayer after completion of sound as:
mediaPlayer = MediaPlayer.create(this,sound);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.reset();
mp.release();
mediaplayer = null;
}
});
mediaPlayer.start();
pass uri instead string
mediaPlayer= MediaPlayer.create(this, Uri.parse(Environment.getExternalStorageDirectory().getPath()+ "/Music/music.mp3"));
mediaPlayer.setLooping(true);
mpintro.start();

Android media player not working as expected

I am very new to android just started with Android currently referring the below code from past 2 days, not able to fix the issue.
Code:
https://github.com/quocnguyenvan/media-player-demo
Issue: Let's say we 4 Songs in the ListView when we click on the first song play it for some time and pause it without clicking on stop.
As soon as we click on the second song the first song starts playing we cannot play the second song unless we click on stop of the first song How to solve this issue.
The issue with code not able to figure out and fix it.I have referred many posts before posting on StackOverflow but could not make it, any suggestion or guidance is highly appreciated.
Problematic code:
// play music
viewHolder.ivPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(flag){
mediaPlayer = MediaPlayer.create(context, music.getSong());
flag = false;
}
if(mediaPlayer.isPlaying()) {
mediaPlayer.pause();
viewHolder.ivPlay.setImageResource(R.drawable.ic_play);
} else {
mediaPlayer.start();
viewHolder.ivPlay.setImageResource(R.drawable.ic_pause);
}
}
});
// stop
viewHolder.ivStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!flag) {
mediaPlayer.stop();
mediaPlayer.release();
flag = true;
}
viewHolder.ivPlay.setImageResource(R.drawable.ic_play);
}
});
These are the steps I used for playing song you can try to sync with my steps to resolve the error.
private void initMembers() {
//initialize the members here
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//media prepare
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(final MediaPlayer mediaPlayer) {
//media player prepared
togglePlayPausePlayer();
}
});
//media completion
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(final MediaPlayer mediaPlayer) {
//handle the media play completion
handleOnCompletionLogic();
}
});
}
after that whenever I try to play the song. I call this method.
public void playMusic(final MusicModel musicModel) {
//here play the music with data in below
try {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
}
mMediaPlayer.reset();
mMediaPlayer.setDataSource(musicModel.getUrl());
mMediaPlayer.prepareAsync();
} catch (IOException | IllegalStateException exp) {
exp.printStackTrace();
showMessage(getString(R.string.error_unable_play));
}
}
above resets the playing song and prepare the player for another song.
and OnPreparedListener it calls the togglePlayPausePlayer() which play and pause the song accordingly.
private void togglePlayPausePlayer() {
//here handle the logic for play and pause the player
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
setPlayAndPause(false);
} else {
mMediaPlayer.start();
setPlayAndPause(true);
}
}
The key is we initialize the player and set an onPrepareListener for the media player to get prepared and then play the song, which will check if it's playing then it will stop and else it will play.
hope this may help you.
For on click on ListView you need to reset the media player, change the data source and start playing with new song.
mp.reset();
mp.setDataSource("song you selected from ListView");
mp.prepare();
mp.start();

I want to play next song automatically in media player

When I click on any song from playlist first time it plays next song, this problem has only happened for the first time on second or more click on any song from the playlist it working fine.
But the major problem has, it unable to play next song after the end of any song anytime.
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.reset();
// play next song
if(listView_click_arg2 < (songPath.length - 1)){
listView_click_arg2=listView_click_arg2+1;
}
else{
// play first song
listView_click_arg2=0;
}
try {
playSong(songPath[listView_click_arg2]);
} catch (IOException e) {
e.printStackTrace();
}
}
});
private void playSong(String path) throws IllegalArgumentException, IllegalStateException, IOException {
startTime=0;
finalTime=0;
oneTimeOnly=0;
mediaPlayer.stop();
mediaPlayer=null;
mediaPlayer=new MediaPlayer();
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();
mediaPlayer.start();
}
I found you have a problem because of mediaPlayer.reset() function. It says
When a MediaPlayer object is just created using new or after reset() is called, it is in the Idle state; and after release() is called, it is in the End state. Between these two states is the life cycle of the MediaPlayer object.
Please go through this link. There is a nice Flow chart:
https://developer.android.com/reference/android/media/MediaPlayer.html
I belive, after you remove mediaPlayer.reset() inside the onCompletionListener body, it will get solved.
Try adding release(). It looks like a out of memory issue.
private void playSong(String path) throws IllegalArgumentException, IllegalStateException, IOException {
startTime=0;
finalTime=0;
oneTimeOnly=0;
// changing the state of mediaPlayer inside its own callback is a bad practice.
//mediaPlayer.stop();
mediaPlayer.release(); // <<------ Add this before reference is gone.
mediaPlayer=null;
mediaPlayer=new MediaPlayer();
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();
mediaPlayer.start();
}

MediaPlayer keep playing even button disabled

I tried most of options avialable on stackoverflow, could you please help me!
I have a button which plays MediaPlayer instance when clicked, but the problem if I click double-click or clicked during playing media it will play two times even i set the button.setEnable(false) and button.setClickable(false), below is the code in Main.java, and I have set in xml android:onClick="playMedia"
MediaPlayer playMedia;
private void playGeneric(MediaPlayer mp, int name, Button button) {
button.setEnabled(false);
button.setClickable(false);
mp = MediaPlayer.create(this, name);
mp.start();
while (mp.isPlaying()) {
}
mp.stop();
mp.release();
mp = null;
button.setEnabled(false);
button.setClickable(false);
}
// play the Media
public void playMedia(View button) {
playGeneric(Media, R.raw.Media, (Button) findViewById(R.id.button1));
}
thanks a lot
1- You should have a single (preferably static) MediaPlayer instance per your activity/service
2- This loop while (mp.isPlaying()) is extremely bad practice, you just need to listen to the appropriate event
3- Before creating a new MediaPlayer instance you have to check that if the current one is not null then stop and release it
To solve your code you can do the following:
1- Let your class implements OnCompletionListener and override the method onCompletion(MediaPlayer mp) to be notified when the MediaPlayer finished and clean the resources (but you need to clean it as well when your activity/service get destroyed)
2-
static MediaPlayer playMedia;
private void playGeneric(MediaPlayer mp, int name, Button button) {
button.setEnabled(false);
button.setClickable(false);
if(mp !=null){
mp.stop();
mp.release();
}
mp = MediaPlayer.create(this, name);
mp.start();
}
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
playMedia = null;
button.setEnabled(true);
button.setClickable(true);
}

Categories