I have 5 songs which i need to play one after the other, and it must loop from the first song after finishing the 5th song.
How do I use the MediaPlayer to achieve this?
public class MediaPlayerExample extends Activity implements MediaPlayer.OnCompletionListener {
int [] songs;
MediaPlayer mediaPlayer;
int current_index = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
songs= new int[] {R.raw.song1,R.raw.song2,R.raw.song3,R.raw.song4};
mediaPlayer = MediaPlayer.create(this, songs[0]);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.start();
}
#Override
public void onCompletion(MediaPlayer mp) {
play();
}
private void play()
{
current_index = (current_index +1)% 4;
AssetFileDescriptor afd = this.getResources().openRawResourceFd(songs[current_index]);
try
{
mediaPlayer.reset();
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
mediaPlayer.prepare();
mediaPlayer.start();
afd.close();
}
catch (IllegalArgumentException e)
{
Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
}
catch (IllegalStateException e)
{
Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
}
catch (IOException e)
{
Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
}
}
}
Simple:
int[] songs = new int[]{R.raw.ab_hai_hamari_bari, R.raw.ab_khel_jamay_ga, R.raw.ab_khel_ke_dikha_psl_official_song, R.raw.chakka_choka_islamabad_united, R.raw.dil_dil_pakistan_junaid, R.raw.duniya_se_aagay, R.raw.hai_jazba_junoon_tho_himmat_na_haar, R.raw.hum_hain_pakistani_junaid, R.raw.jeet_ki_lagan, R.raw.jeetay_ga_pakistan_dedicate, R.raw.josh_e_junoon_pakistan_cricket, R.raw.karachi_kings_official, R.raw.lahore_qalandar_official, R.raw.multan_sultan_official, R.raw.peshawar_zalmi, R.raw.quetta_gladiator, R.raw.stand_up_for_the_champions};
you need to use CountDownTimer for this. CountDown timer has give you facility to do this one by one ::
MediaPlayer mp_xmPlayer2 = new MediaPlayer();
mp_xmPlayer2 = MediaPlayer.create(this, R.raw.bg_music_wav);
for(int i=0;i<5;i++)
{
CountDownTimer cntr_aCounter = new CountDownTimer(3000, 1000) {
public void onTick(long millisUntilFinished) {
mp_xmPlayer2.start();
}
public void onFinish() {
//change music name
}
};
cntr_aCounter.start();
}
Related
I am having 3 tones. I am calling playmusic() function to play 2 of these tones on imageview toggle. when i click on imageview for first time tone1 starts playing. when i click 2nd time on the same imageview tone2 starts playing, but tone1 is not stopped.
my requiremet is , when i click on imageview for -
(1st time - tone1 should start playing).
(2nd time - tone1 should stop playing and tone2 should start playing)
(3rd time - tone2 should stop playing and tone1 should start playing again)
and so on....
String file=null;
int x=0;
public void playMusic(int i) {
x=i;
if(i==1){
file = R.raw.tone1;
}else if(i==2){
file = R.raw.tone2;
}else{
file = R.raw.tone3;
}
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
AssetFileDescriptor assetFileDescriptor =
Main2Activity.this.getResources().openRawResourceFd(file);
if(assetFileDescriptor == null) return;
try {
mediaPlayer.setDataSource(
assetFileDescriptor.getFileDescriptor(),
assetFileDescriptor.getStartOffset(),
assetFileDescriptor.getLength()
);
assetFileDescriptor.close();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if(mediaPlayer != null){
mediaPlayer.release();
mediaPlayer = null;
}
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(final MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
// HelpFunctions.showLog("ERROR = " + e);
} catch (IllegalStateException e) {
// HelpFunctions.showLog("ERROR = " + e);
} catch (IOException e) {
// HelpFunctions.showLog("ERROR = " + e);
}
}
I did a small modification on your logic and added mediaplayer.reset(). Here is the solution link
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView player = findViewById(R.id.play);
player.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
playMusic(1);
}
});
mediaPlayer = new MediaPlayer();
}
int file = 0;
MediaPlayer mediaPlayer;
int x = 0;
public void playMusic(int i) {
x = x + i;
if (x == 1) {
file = R.raw.tone1;
}
else if (x == 2) {
file = R.raw.tone2;
} else {
x = 0;
file = R.raw.tone3;
}
mediaPlayer.reset();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
AssetFileDescriptor assetFileDescriptor =
MainActivity.this.getResources().openRawResourceFd(file);
if (assetFileDescriptor == null) return;
try {
mediaPlayer.setDataSource(
assetFileDescriptor.getFileDescriptor(),
assetFileDescriptor.getStartOffset(),
assetFileDescriptor.getLength()
);
assetFileDescriptor.close();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if (mediaPlayer != null) {
mediaPlayer.release();
}
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(final MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
// HelpFunctions.showLog("ERROR = " + e);
} catch (IllegalStateException e) {
// HelpFunctions.showLog("ERROR = " + e);
} catch (IOException e) {
// HelpFunctions.showLog("ERROR = " + e);
}
}
}
when i click 2nd time on the same imageview tone2 starts playing, but tone1 is not stopped.
If that's the only issue, try putting the following line before you call mediaPlayer = new MediaPlayer();:
if (mediaPlayer != null && mediaPlayer.isPlaying()) mediaPlayer.stop();
im newbie here, can you help me?? i want to play all song in my raw folder sequentially, after all song finished playing i want no looping.
i have tried this code but it keeps looping after allsong playing
{
int [] sound;
int soundke = 0;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kubus);
sound = new int[] {R.raw.swoosh2, R.raw.swoosh1, R.raw.swoosh2};
mediaPlayer = MediaPlayer.create(kubus.this, sound[0]);
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
play();
}
});
}
private void play () {
soundke = (soundke + 1) % 3;
AssetFileDescriptor afd = this.getResources().openRawResourceFd(sound[soundke]);
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
mediaPlayer.prepare();
mediaPlayer.start();
afd.close();
} catch (IOException e) {
}
}
it still keeps looping after all song playing. i want not looping after all song playing, thanks for your helping
int [] sound;
int soundke = 0;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kubus);
sound = new int[] {R.raw.swoosh2, R.raw.swoosh1, R.raw.swoosh2};
mediaPlayer = MediaPlayer.create(kubus.this, sound[0]);
mediaPlayer.setLooping(false);
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if(soundke < sound.length-1){
play(++soundke);
}else{
soundke=0;
mediaPlayer.stop();
}
}
});
}
private void play (int track) {
//soundke = (soundke + 1) % 3;
AssetFileDescriptor afd = this.getResources().openRawResourceFd(sound[track]);
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
mediaPlayer.setLooping(false);
mediaPlayer.prepare();
mediaPlayer.start();
afd.close();
} catch (IOException e) {
}
}
I am trying to play an audio file when the app started, but I am getting an error says that start called in state 1 Error (-38,0), here is my code:
public void audioPlayer(){
//set up MediaPlayer
MediaPlayer mp = new MediaPlayer();
try {
mp.create(this, R.raw.music);
onPrepared(mp);
} catch (Exception e) {
e.printStackTrace();
}
}
public void onPrepared(MediaPlayer mp) {
mp.start();
}
public void audioPlayer(){
MediaPlayer mp = new MediaPlayer();
mp.setOnPreparedListener(mListener);
try {
mp.setDataSource(this, R.raw.music);
mp.prepare();
} catch (Exception e) {
e.printStackTrace();
}
}
private OnPreparedListener mListener=new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
};
i'm adding multiple audio files using
try {
MediaPlayer mp = MediaPlayer.create(context, R.raw.play);
audioArr[0] = mp;
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mp.prepare();
} catch (Exception e) {
e.printStackTrace();
}
and releasing media in a function as
for (MediaPlayer media : audioList) {
if (media != null) {
if(media.isPlaying())
media.stop();
media.release();
media = null;
}
}
stil i'm not able to play multiple audio file in my application,first time playing with audio,so kindly guide
Try this :
void addSongs()
{
File songs = new File(sdPath); //sdPath is the path of your audio files
if(songs.listFiles(new SongFilter()).length > 0)
{
for(File file : songs.listFiles(new SongFilter()))
{
vector.add(file.getName());
}
arrayAdapter.setNotifyOnChange(true); //arrayAdapter Array Adapter
songList.setAdapter(arrayAdapter); //songList is a ListView
}
}
SongFilter Class like this :
class SongFilter implements FilenameFilter
{
public boolean accept(File dir, String filename)
{
return (filename.endsWith(".mp3"));
}
}
buttonSound.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// play another sound here.do your stuff whatever you want to do
mp.stop();
}
});
public class AudioActivity extends Activity implements MediaPlayer.OnCompletionListener {
int [] songs;
MediaPlayer mediaPlayer;
int current_index = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {##}
private void start(){
songs= new int[] {R.raw.s1,R.raw.s2,R.raw.s3,R.raw.s4};
mediaPlayer = MediaPlayer.create(this, songs[0]);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.start();
}
#Override
public void onCompletion(MediaPlayer mp) {
**// This is the completion listener registered with mediaplayer instance.**
playNextSong();
}
private void playNextSong()
{
current_index = (current_index +1)% songs.length;
AssetFileDescriptor afd = this.getResources().openRawResourceFd(songs[current_index]);
if(current_index!=0){
try
{
mediaPlayer.reset();
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
mediaPlayer.prepare();
mediaPlayer.start();
afd.close();
}
catch (IllegalArgumentException e){}
catch (IllegalStateException e){}
catch (IOException e){}
}else{
mediaPlayer.stop();
}
}
}
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();
}