How to play sound onclick of button in layout? - android

I have a layout in which multiple button is showing.onclick of button one sound play respectively.My code is like as but its not work:-
#Override
public void onClick(View view) {
resetPlayer();
int index = 0;
if (view.equals(objbutton1))
index = R.raw.sound1;
while (true) {
this.objplayer = MediaPlayer.create(this, index);
this.objplayer.setLooping(false);
this.objplayer.start();
this.objplayer
.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
MainActivity.this.objplayer.release();
MainActivity.this.objplayer = null;
}
}
);
if(view.equals(objbutton2))
{
index=R.raw.sound2;
continue;
}
if(view.equals(objbutton3))
{
index=R.raw.sound3;
continue;
}
if(view.equals(objbutton4))
{
index=R.raw.sound4;
continue;
}
if(view.equals(objbutton5))
{
index=R.raw.sound5;
continue;
}
break;
}
}
private void resetPlayer() {
if (this.objplayer != null) {
if (this.objplayer.isPlaying())
this.objplayer.stop();
this.objplayer.release();
this.objplayer = null;
}
App is playing only one sound and when click other button no sound be changed

Use this
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), index);
mp.start();
Like...
private MediaPlayer mp; // declare it in public area.
public void onClick(View view) {
int index = 0;
if (view.equals(objbutton1)){
index = R.raw.sound1;
if(mp !=null && mp.isPlaying()) mp.stop();
mp = MediaPlayer.create(getApplicationContext(), index);
mp.start();
}
if(view.equals(objbutton2))
{
index=R.raw.sound2;
if(mp !=null && mp.isPlaying()) mp.stop();
mp = MediaPlayer.create(getApplicationContext(), index);
mp.start();
}
if(view.equals(objbutton3))
{
index=R.raw.sound3;
if(mp !=null && mp.isPlaying()) mp.stop();
mp = MediaPlayer.create(getApplicationContext(), index);
mp.start();
}
if(view.equals(objbutton4))
{
index=R.raw.sound4;
if(mp !=null && mp.isPlaying()) mp.stop();
mp = MediaPlayer.create(getApplicationContext(), index);
mp.start();
}
if(view.equals(objbutton5))
{
index=R.raw.sound5
if(mp !=null && mp.isPlaying()) mp.stop();
mp = MediaPlayer.create(getApplicationContext(), index);
mp.start();
}
}
And in onDestroy()put this mp.release();

Related

Play mp3 files one after the other with little delay with more elegant code?

I need to play multiple (correct :2 ) mp3 files loaded from my assets when a button is clicked. If the button is again clicked 2 new songs should be played and the old ones should be stopped immidiatelly.The process is on going...
At the moment I have achieved this by stupidly creating 2 mediaPlayer instances in 2 separate methods that basically have the same body .
The caller is an onTouch method and ,within it, first I call method 1 ,then sleep for 2 secs ,then call method 2. I m sure there must be a way for this to be more elegant code? For example I have implemented some listeners that are just sitting there (Actually tried to make this work but totally screwed up with Illegal States all over the place ). Ideally I would like to use 1 MediaPlayer and one method for playing every sound in my app.
int carouzelIndex = 0
#Override
public boolean onTouch(MotionEvent e, int scaledX, int scaledY) {
...
if (e.getAction() == MotionEvent.ACTION_UP) {
carouzelIndex++;
Assets.playMusic1("music1.ogg",false);
Thread thread = new Thread(){
public void run(){
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Assets.playMusic2("music2.ogg",false);
}
}
}
}
Now my player methods 1 and 2 (playMusic1() and playMusic2() )are the same. Both are instansiating different MediaPlayers and for the shake of simplicity I write just one copy in the post
Public class Assets
MediaPlayer mediaPlayer;
public static void playMusic(String filename, boolean looping) {
AssetFileDescriptor afd = null;
Log.d("Assets", "playing music");
if (mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(looping);
}
try {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(looping);
}
afd = GameMainActivity.assets.openFd(filename);
mediaPlayer.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
afd.close();
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if (!mp.isPlaying())
mp.start();
}
});
mediaPlayer.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
});
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayerIsFinished = true;
mp.reset();
}
});
mediaPlayer.setOnInfoListener(new OnInfoListener() {
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
return false;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
For immediate playback you need two MediaPlayer set up and chained together via OnCompletionListener
You can do it like this:
Note that I also deleted some unnecessary overrides, you might add them again if you need them.
Public class Assets{
MediaPlayer mediaPlayer;
MediaPlayer mediaPlayer2;
boolean mediaplayer2prepared = false;
boolean mediaplayer1finished = false;
public static void playMusic(String filename, boolean looping, String filename2, boolean looping2) {
AssetFileDescriptor afd = null;
Log.d("Assets", "playing music");
if (mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(looping);
mediaplayer1finished = false;
}
if (mediaPlayer2 == null) {
mediaPlayer2 = new MediaPlayer();
mediaPlayer2.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer2.setLooping(looping);
mediaplayer2prepared = false;
}
try {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(looping);
mediaplayer1finished = false;
}
if (mediaPlayer2 != null) {
mediaPlayer2.stop();
mediaPlayer2.release();
mediaPlayer2 = new MediaPlayer();
mediaplayer2prepared = false;
mediaPlayer2.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer2.setLooping(looping);
}
afd = GameMainActivity.assets.openFd(filename);
mediaPlayer.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
afd.close();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if (!mp.isPlaying())
mp.start();
}
});
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayerIsFinished = true;
mp.reset();
if(mediaplayer2prepared)
mediaplayer2.start();
mediaplayer1finished = true;
}
});
mediaPlayer.prepareAsync();
afd2 = GameMainActivity.assets.openFd(filename2);
mediaPlayer2.setDataSource(afd2.getFileDescriptor(),
afd2.getStartOffset(), afd2.getLength());
afd2.close();
mediaPlayer2.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayerIsFinished = true;
mp.reset();
mediaplayer2prepared = true;
if(mediaplayer1finished && !mp.isPlaying()){
mp.start();
}
}
});
mediaPlayer2.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayerIsFinished = true;
mp.reset();
}
});
mediaPlayer2.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
}
}
To start both mediaplayers in succession simply do Assets.playMusic("music1.ogg",false, "music2.ogg",false);
You can try something like this. Use a single mediaplayer in a single thread. It is an asynchronous operation so it will go on also if the thread is paused. I think it would work.
private Thread t = null;
private MediaPlayer mediaPlayer;
...
Button b=findViewById(R.id.yourButtonId);
b.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
//if button had previously clicked stop audio reproduction
if(mediaPlayer.isPlaying()) mediaPlayer.stop();
if(t.isAlive()) t.stop();
String[] files;
//Here you have to set your filenames in the array
...
...
//Now play that audio
playMusic(files, false);
}
});
...
protected static void playMusic(String[] files, boolean looping){
AssetFileDescriptor afd = null;
Log.e("Assets", "Playing music");
t=new Thread(){
#Override
public void run(){
//Initialize mediaPlayer
for(String filename:files){
mediaPlayer=new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(looping);
afd = GameMainAcivity.assets.openFd(filename);
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),afd.getLength());
afd.close();
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp){
if(!mp.isPlaying()) mp.start();
}
});
//while audio is playing wait in this position
while(mediaPlayer.isPlaying()){
this.wait(100);
}
//now loop can restart with the other filename that has
//to be reproduced
}
}
};
t.start();
}

How to define the button to play Z if Y is already playing?

the idea is that i have 1 button and 2 states.
1. On press is playing sound Z (from a random sound list)
2. On second press: if Z.isPlaying play Y
All seems fine, till i press it 3 times in a row, and get a nullpointerexception
Here is the onClick code:
#Override
public void onClick(View view) {
if (view.getId() == R.id.goat) {
if(Piciu != null) {
if(mp2.isPlaying()){mp2.stop();mp2.reset();mp2.release();mp2 = null;}
butGoat.setBackgroundResource(R.drawable.goat96);
mp3 = MediaPlayer.create(this, R.raw.cow);
mp3.start();
butGoat.setBackgroundResource(R.drawable.goat96);
mp3.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp3) {
butGoat.destroyDrawingCache();
butGoat.setBackgroundResource(R.anim.clipeala);
yourAnimation = (AnimationDrawable) butGoat.getBackground();
yourAnimation.start();
Piciu = null;
}
});
toast.setText("I can`t yell so Fast!");
toast.setGravity(Gravity.BOTTOM, 0, 0);
toast.show();
} else {
Piciu = mp2;
butGoat.destroyDrawingCache();
butGoat.setBackgroundResource(R.drawable.goat96);
Random r = new Random();
int Low = 0;
int High = 16;
int rndm = r.nextInt(High-Low) + Low;
mp2 = MediaPlayer.create(getApplicationContext(),sounds[rndm]);
mp2.start();
mp2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp2) {
butGoat.setBackgroundResource(R.anim.clipeala);
yourAnimation = (AnimationDrawable) butGoat.getBackground();
yourAnimation.start();
mp2.reset();
mp2.release();
mp2 = null;
Piciu = null;
}
});
}
}
}
i just can't understand Why do i get nullpointerexception if Sound Z is not playing.
I see you didn't check for mp2 != null before calling mp2.isPlaying():
if (view.getId() == R.id.goat) {
if(Piciu != null) {
if(mp2.isPlaying()){mp2.stop();mp2.reset();mp2.release();mp2 = null;}
change it to if (Piciu != null && mp2 != null) Also not sure why you need the Piciu variable at all. I'd clear up the logic first, then cleanup the code if it's still crashing.

Playing Image and audio simulteniously in android

I am trying to play audio and image concurrently in android...i have take one image-view and two buttons for go to back and go to next..when i click on next button and go on its working perfectly fine but as soon as i clicked on back button only audio file changes not the image. if i again clicked on back button then image changes but with another audio file..please help me out with this..thanks here is my code
public class Main extends Activity{
Button btn_back,btn_play,btn_next;
ImageView img_view;
int current_img = 0;
int current_aud = 0;
MediaPlayer mp;
int[] images = {R.drawable.img1,R.drawable.img2,R.drawable.img3,R.drawable.img4,R.drawable.img5,
R.drawable.img6,R.drawable.img7,R.drawable.img8,R.drawable.img9,R.drawable.img10,
R.drawable.img11,R.drawable.img12};
int[] audio = {R.raw.aud,R.raw.a,R.raw.aud,R.raw.a,R.raw.aud,R.raw.a,R.raw.aud,R.raw.a,
R.raw.aud,R.raw.a,R.raw.aud,R.raw.a};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_back = (Button)findViewById(R.id.button1);
btn_play = (Button)findViewById(R.id.button2);
btn_next = (Button)findViewById(R.id.button3);
img_view = (ImageView)findViewById(R.id.imageView1);
img_view.setImageResource(R.drawable.ic_launcher);
mp =new MediaPlayer();
btn_play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp.stop();
}
});
btn_next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
current_img = current_img % images.length;
img_view.setImageResource(images[current_img]);
current_img ++;
try {
if(mp != null){
if(mp.isPlaying()){
mp.stop();
// mp.release();
}
}
current_aud = current_aud % audio.length;
mp.reset();
mp = MediaPlayer.create(Main.this, audio[current_aud]);
mp.start();
current_aud ++;
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
});
btn_back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
current_img = (current_img + images.length) % images.length;
current_img --;
img_view.setImageResource(images[current_img]);
try {
if(mp != null){
if(mp.isPlaying()){
mp.stop();
// mp.reset();
}
}
current_aud = (current_aud + audio.length)% audio.length;
mp.reset();
mp = MediaPlayer.create(Main.this, audio[current_aud]);
current_aud --;
mp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
});
public class Main extends Activity implements OnClickListener{
Button btn_back,btn_play,btn_next;
ImageView img_view;
int current_img = 0;
int current_aud = 0;
MediaPlayer mp;
int[] images = {R.drawable.img1,R.drawable.img2,R.drawable.img3,R.drawable.img4,R.drawable.img5,
R.drawable.img6,R.drawable.img7,R.drawable.img8,R.drawable.img9,R.drawable.img10,
R.drawable.img11,R.drawable.img12};
int[] audio = {R.raw.aud,R.raw.a,R.raw.aud,R.raw.a,R.raw.aud,R.raw.a,R.raw.aud,R.raw.a,
R.raw.aud,R.raw.a,R.raw.aud,R.raw.a};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_back = (Button)findViewById(R.id.button1);
btn_play = (Button)findViewById(R.id.button2);
btn_next = (Button)findViewById(R.id.button3);
img_view = (ImageView)findViewById(R.id.imageView1);
img_view.setImageResource(R.drawable.ic_launcher);
mp =new MediaPlayer();
btn_play.setOnClickListener(this);
btn_next.setOnClickListener(this);
btn_back.setOnClickListener(this);
}
#Override
public void OnClick(View view){
switch(view.getId()){
case R.id.button1:
current_img --;
if(current_img == -1){
current_img = images.length-1;
}
img_view.setImageResource(images[current_img]);
if(mp != null && mp.isPlaying()){
mp.stop();
}
current_aud--;
if(current_aud == -1){
current_aud = audio.length-1;
}
mp.reset();
mp = MediaPlayer.create(Main.this, audio[current_aud]);
current_aud --;
mp.start();
break;
case R.id.button3:
current_img ++;
if(current_img == images.length){
current_img = 0;
}
img_view.setImageResource(images[current_img]);
if(mp != null && mp.isPlaying()){
mp.stop();
}
current_aud++;
if(current_aud == audio.length){
current_aud = 0;
}
mp.reset();
mp = MediaPlayer.create(Main.this, audio[current_aud]);
current_aud --;
mp.start();
break;
case R.id.button2:
if(mp != null && mp.isPlaying()){
mp.stop();
}
break;
}
}
}
You just have to change this for Next
if (currentimg < (media_list.size())) {
currentimg+= 1;
} else {
currentimg = 0;
}
and for back
if (currentimg > 0) {
currentimg -= 1;
} else {
currentimg = 0;
}
Just add it. It should work

Android MediaPlayer can't stop

I have a code fragment in my BrocardcastReceiver like this:
if (cmd != null && cmd.equals(PLAY_SOUND)) {
Log.i("mp", "mp has already been prepared ");
mp.setLooping(true);
mp.start();
return;
}
if (cmd != null && cmd.equals(STOP_SOUND) && mp != null) {
if (mp.isLooping()) {
mp.setLooping(false);
}
mp.stop();
mp.release();
return;
}
It aims to control alarming or stop alarming. I can make mp run successfully, but when I want to stop it, mp is null. How can I stop mp from being changed?
try this
in your code
stopPlaying();
and declare this methode .
private void stopPlaying() {
if (player1 != null) {
player1.stop();
player1.release();
player1 = null;
}
}

Playing audio files one after another

I have a list of audio files like this,
int music_numbers[] = { R.raw.one, R.raw.two, R.raw.three, R.raw.four,
R.raw.five, R.raw.six, R.raw.seven, R.raw.eight, R.raw.nine };
I need to play this one by one - when i send 100 to this play_numbers method - i am intend to play digit wise..
I have done this - but i unable to do this one after another..
private void _play_numbers(final String i) {
// TODO Auto-generated method stub
mPlayer = MediaPlayer.create(PlayFileActivity.this, R.raw.payment);
mPlayer.start();
mPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mPlayer.stop();
myDigit = i.charAt(1) + "";
_function_play_file(Integer.parseInt(myDigit));
}
});
}
in _function_play_file - i have this
void _function_play_file(int files) {
switch (files) {
case 0:
mPlayer = MediaPlayer.create(this, music_numbers[0]);
mPlayer.start();
case 1:
mPlayer = MediaPlayer.create(this, music_numbers[1]);
mPlayer.start();
case 2:
mPlayer = MediaPlayer.create(this, music_numbers[2]);
mPlayer.start();
case 3:
mPlayer = MediaPlayer.create(this, music_numbers[3]);
mPlayer.start();
case 4:
mPlayer = MediaPlayer.create(this, music_numbers[4]);
mPlayer.start();
case 5:
mPlayer = MediaPlayer.create(this, music_numbers[5]);
mPlayer.start();
case 6:
mPlayer = MediaPlayer.create(this, music_numbers[6]);
mPlayer.start();
case 7:
mPlayer = MediaPlayer.create(this, music_numbers[7]);
mPlayer.start();
case 8:
mPlayer = MediaPlayer.create(this, music_numbers[8]);
mPlayer.start();
case 9:
mPlayer = MediaPlayer.create(this, music_numbers[9]);
mPlayer.start();
case 10:
mPlayer = MediaPlayer.create(this, music_numbers[10]);
mPlayer.start();
}
}
You need to set an onCompletionListener to each and start the next one on completion.
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
// Code to start the next audio in the sequence
}
});
The best way to achieve this is to create a class that implements OnCompletionListener which handles the onCompletion and receives the next file to play. This way you can instantiate it nicely in your code.
Of course, don't forget your break; in the cases above.
Use a queue for holding the numbers to be played.
private void _play_numbers(final String i) {
// e.g '100': put '1', '0', '0' in a Queue after converting to digits
Queue queue = new LinkedList();
//Use the add method to add items.
myDigit = // remove next digit from queue..
_function_play_file(myDigit);
}
void _function_play_file(int files) {
switch(files) {
case 0:
mPlayer = MediaPlayer.create(PlayFileActivity.this, R.raw.payment);
mPlayer.setOnCompletionListener(completeListener );
mPlayer.start();
break;
.....
}
OnCompletionListener completeListener = new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
myDigit = // remove next digit from queue..
if (myDigit != -1) // if queue is not empty..
_function_play_file(myDigit);
}
});
}
This code works for me,but i place the audio files in assets folder:
//define a variable to be used as index.
int audioindex = 0;
//Extract the files into an array
String[] files = null;
files = assetManager.list("audiofiles");
mp.setOnCompletionListener(new OnCompletionListener(){
// #Override
public void onCompletion(MediaPlayer arg0) {
// File has ended, play the next one.
FunctionPlayFile(files[audioindex]);
audioindex+=1; //increment the index to get the next audiofile
}
});
This is working code for playing songs in continue loop
public class MainActivity extends Activity
{
private int[] tracks = {R.raw.explosion,R.raw.pianothingy_one,R.raw.car_horn_x};
int mCompleted = 0;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaPlayer mp = MediaPlayer.create(this, tracks[0]);
mp.setOnCompletionListener(new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
mCompleted++;
mp.reset();
if (mCompleted < tracks.length)
{
try
{
AssetFileDescriptor afd = getResources().openRawResourceFd(tracks[mCompleted]);
if (afd != null)
{
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mp.prepare();
mp.start();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else if (mCompleted>=tracks.length)
{
mCompleted =0;
try
{
AssetFileDescriptor afd = getResources().openRawResourceFd(tracks[mCompleted]);
if (afd != null)
{
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mp.prepare();
mp.start();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else
{
mCompleted=0;
mp.release();
mp = null;
}
}
});
mp.start();
use PlayMedia Like this
int[] soundIDs = {R.raw.yes, R.raw.eat};
PlayMedia playAudio = new PlayMedia(context,soundIDs);
playAudio.execute();
and define PlayMedia Class Like this
import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.util.Log;
public class PlayMedia extends AsyncTask<Void, Void, Void> {
private static final String LOG_TAG = PlayMedia.class.getSimpleName();
Context context;
private MediaPlayer mediaPlayer;
int[] soundIDs;
int idx =1;
public PlayMedia(MediaPlayer mediaPlayer) {
this.mediaPlayer = mediaPlayer;
}
public PlayMedia(final Context context, final int[] soundIDs) {
this.context = context;
this.soundIDs=soundIDs;
mediaPlayer = MediaPlayer.create(context,soundIDs[0]);
setNextMediaForMediaPlayer(mediaPlayer);
}
public void setNextMediaForMediaPlayer(MediaPlayer player){
player.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
if(soundIDs.length>idx){
mp.release();
mp = MediaPlayer.create(context,soundIDs[idx]);
setNextMediaForMediaPlayer(mp);
mp.start();
idx+=1;
}
}
});
}
#Override
protected Void doInBackground(Void... params) {
try {
mediaPlayer.start();
} catch (IllegalArgumentException e) {
Log.e(LOG_TAG, "", e);
} catch (SecurityException e) {
Log.e(LOG_TAG, "", e);
} catch (IllegalStateException e) {
Log.e(LOG_TAG, "", e);
}
return null;
}
}
For me the issue was that I was calling mediaPlayer.prepare() without first calling mediaPlayer.reset().
All good now.
MediaPlayer mediaplayer = new MediaPlayer();
setSound(file );
try {
if(mediaplayer != null)
{
mediaplayer.stop();
mediaplayer.release();
}
mediaplayer.setDataSource(getResources().openRawResourceFd(file)
.getFileDescriptor());
mediaplayer.prepare();
mediaplayer = MediaPlayer.create(getBaseContext(), now);
mediaplayer.start();
mediaplayer.setLooping(false);
mediaplayer.setLooping(true); //sequence playing
} catch (NullPointerException e) {
e.printStackTrace();
}

Categories

Resources