Auto playing songs in a list? - android

I read through a tutorial and created a simple music player dubbed SimplePlayer. When I click the song I want to play, it plays perfectly fine.
However, when that song finishes, instead of playing the next song it plays the second song in the list, then keeps playing it over and over again.
I know that the choosing of the song when the first song finishes is inside the onCompletion method with the mp.setDataSource, but I'm not sure what I need to put in the brackets other than the +1 so that it plays the next song in the list:
public void onCompletion(MediaPlayer mp) {
try {
mp.reset();
mp.setDataSource(SD_PATH + songs.get(+1));
mp.prepare();
mp.start();
play.setEnabled(false);
pause.setEnabled(true);
stop.setEnabled(true);
} catch(IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
Here is the rest of the code in case I have to change something there as well:
public class MainActivity extends ListActivity implements OnCompletionListener {
private static final String SD_PATH = new String(Environment.getExternalStorageDirectory().getPath() + "/");
private List<String> songs = new ArrayList<String>();
private MediaPlayer mp = new MediaPlayer();
private View play;
private View pause;
private View stop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updatePlaylist();
play = (ImageButton)findViewById(R.id.imageButton1);
pause = (ImageButton)findViewById(R.id.imageButton2);
stop = (ImageButton)findViewById(R.id.imageButton3);
mp.setOnCompletionListener(this);
play.setEnabled(false);
pause.setEnabled(false);
stop.setEnabled(false);
}
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
try {
mp.reset();
mp.setDataSource(SD_PATH + songs.get(position));
mp.prepare();
mp.start();
play.setEnabled(false);
pause.setEnabled(true);
stop.setEnabled(true);
} catch(IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
private void updatePlaylist() {
File home = new File(SD_PATH);
if (home.listFiles(new Mp3Filter()).length > 0) {
for (File file : home.listFiles( new Mp3Filter())) {
songs.add(file.getName());
}
ArrayAdapter<String> songList = new ArrayAdapter<String>(this,R.layout.song_item,songs);
setListAdapter(songList);
}
}
public void play(View view){
Toast.makeText(getApplicationContext(), "Playing song",
Toast.LENGTH_SHORT).show();
mp.start();
play.setEnabled(false);
pause.setEnabled(true);
stop.setEnabled(true);
}
public void pause(View view){
Toast.makeText(getApplicationContext(), "Pausing song",
Toast.LENGTH_SHORT).show();
mp.pause();
play.setEnabled(true);
pause.setEnabled(false);
stop.setEnabled(true);
}
public void stop(View view){
Toast.makeText(getApplicationContext(), "Stopping song",
Toast.LENGTH_SHORT).show();
mp.stop();
play.setEnabled(false);
pause.setEnabled(false);
stop.setEnabled(false);
}
#Override
public void onCompletion(MediaPlayer mp) {
try {
mp.reset();
mp.setDataSource(SD_PATH + songs.get(+1));
mp.prepare();
mp.start();
play.setEnabled(false);
pause.setEnabled(true);
stop.setEnabled(true);
} catch(IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
}
also, how can I make it so that when the app runs, it lists all songs on the sdcard, the phone storage and in the folders on the sdcard? At the moment it only lists the songs on the root of the sdcard.

What you have written is for continuously playing second song.
You need to use a global variable to indicate song number and increment it and pass that to setDataSource();
First,create a public global variable
public static int SONG_NUMBER=0;
In your onCompletion method
#Override
public void onCompletion(MediaPlayer mp) {
try {
mp.reset();
if(SONG_NUMBER == songs.size())
{
SONG_NUMBER=0;
}
else
{
SONG_NUMBER=SONG_NUMBER+1;
}
mp.setDataSource(SD_PATH + songs.get(SONG_NUMBER));// pass SONG_NUMBER++ instead +1
mp.prepare();
mp.start();
play.setEnabled(false);
pause.setEnabled(true);
stop.setEnabled(true);
} catch(IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
In your on ListItemClick method,assign SONG_NUMBER based on position
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
try {
SONG_NUMBER=position; // <------------------------add this line
mp.reset();
mp.setDataSource(SD_PATH + songs.get(position));
mp.prepare();
mp.start();
play.setEnabled(false);
pause.setEnabled(true);
stop.setEnabled(true);
} catch(IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}

Related

How to play audio on button click (recycler view)

How do I play an audio from raw folder on button click? Here, I'm using recyclerview to show the list of audios. But when click play, it doesn't play any sound.
private Button btnPlay;
btnPlay = (Button) findViewById(R.id.btnPlay);
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp = new MediaPlayer();
try{
mp.setDataSource(ss.getSoundURI());
mp.prepare();
mp.start();
} catch (Exception e){
e.printStackTrace();
}
}
});
You can use this function:
public void playSound(final String fileName) {
MediaPlayer mpPlayer = null;
try {
int fileId = getResources().getIdentifier(fileName, "raw", getPackageName());
mpPlayer = MediaPlayer.create(this, fileId);
mpPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mpPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mpPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
} catch (Exception e) {
e.printStackTrace();
if (mpPlayer != null)
mpPlayer.release();
}
}
NOTE: use file name without file extension. for example if your file name is file1.wav you should send file1 as a file name to function NOT file1.wav .
NOTE: In first line I defined the mpPlayer and initialize it because i want to use it in the catch block.

How to play and pause audio in firebase recyclerview in android

I am developing an app in which I have to fetch audio from firebase. I am using firebase recycler view. I am getting a problem that when I click the first song it plays good, but when I click second item then the first song's play button does not change and seekbar of first and second song changes.
Here is the code.
holder.play_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String audioUrl3 = model.getMedia();
if (!isPlaying){
if (mPlayer!=null){
mPlayer.release();
}
Toast.makeText(mContext, "Loading....", Toast.LENGTH_SHORT).show();
isPlaying = true;
Uri uri = Uri.parse(audioUrl3);
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.reset();
try {
mPlayer.setDataSource(mContext,uri);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(mContext, "Error Occured", Toast.LENGTH_SHORT).show();
}
try{
mPlayer.prepareAsync();
}catch (Exception e){
Toast.makeText(mContext, "Error Occured", Toast.LENGTH_SHORT).show();
holder.play_btn.setImageDrawable(holder.play_btn.getContext().getResources().getDrawable(R.drawable.ic_play));
}
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if(mPlayer.isPlaying()){
mPlayer.stop();
}
mPlayer.start();
holder.play_btn.setImageDrawable(holder.play_btn.getContext().getResources().getDrawable(R.drawable.ic_pause));
holder.seekBar.setMax(mPlayer.getDuration());
Toast.makeText(mContext, "Playing...", Toast.LENGTH_SHORT).show();
updateSeekBar(holder.seekBar);
}
});
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
holder.play_btn.setImageDrawable(holder.play_btn.getContext().getResources().getDrawable(R.drawable.ic_play));
isPlaying = false;
}
});
}
else {
isPlaying=false;
stopPlaying();
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer=null;
holder.play_btn.setImageDrawable(holder.play_btn.getContext().getResources().getDrawable(R.drawable.ic_play));
}
});
}
private void updateSeekBar(final SeekBar seek) {
try{
int pos = mPlayer.getCurrentPosition();
seek.setProgress(pos);
}catch (Exception e){
}
runnable = new Runnable() {
#Override
public void run() {
updateSeekBar(seek);
}
};
handler.postDelayed(runnable, 1800);
}

adding mutiple audio file in android

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();
}
}
}

Setting an array of songs using MediaPlayer

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();
}

android : use of media

I want to make application that gives me the list of audio files available in my SDCard and then i should be able to play that audio file from my application. And even pause resume audio playback etc. and function..
Any help on that?
You can see the below code for streaming audio from URL
private void playVideo() {
try {
final String path = "http://www.a1freesoundeffects.com/animals12557/catmeow.wav";
// If the path has not changed, just start the media player
if (path.equals(current) && mp != null) {
mp.start();
return;
}
current = path;
// Create a new media player and set the listeners
mp = new MediaPlayer();
mp.setDataSource(path);
mp.prepare();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (Exception e) {
if (mp != null) {
mp.stop();
mp.release();
}
}
}
You can try this way.
class Mp3Filter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".mp3"));
}
}
public class AudioPlayer extends ListActivity implements OnClickListener{
private static final String MEDIA_PATH = new String("/sdcard/backup/songs");
private List<String> songs = new ArrayList<String>();
private MediaPlayer mp = new MediaPlayer();
private int currentPosition = 0;
private static final String TAG = "Audio Player Demo ";
private static final String isPlaying = "Media is Playing";
private static final String notPlaying = "Media has stopped Playing";
Button playerButton;
public void onClick(View v) {
if (v.getId() == R.id.play) {
playPause();
}
}
#Override
public void onCreate(Bundle icicle) {
try {
super.onCreate(icicle);
setContentView(R.layout.songlist);
playerButton = (Button) this.findViewById(R.id.play);
playerButton.setText(R.string.stop_label);
playerButton.setOnClickListener(this);
updateSongList();
//demoPlay();
} catch (NullPointerException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
public void updateSongList() {
File home = new File(MEDIA_PATH);
if (home.listFiles( new Mp3Filter()).length > 0) {
for (File file : home.listFiles( new Mp3Filter())) {
songs.add(file.getName());
}
ArrayAdapter<String> songList = new ArrayAdapter<String>(this,R.layout.song_item,songs);
setListAdapter(songList);
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
currentPosition = position;
playSong(MEDIA_PATH + songs.get(position));
}
private void playSong(String songPath) {
try {
mp.reset();
mp.setDataSource(songPath);
mp.prepare();
mp.start();
// Setup listener so next song starts automatically
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer arg0) {
nextSong();}
});
} catch(IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
private void nextSong() {
if (++currentPosition >= songs.size()) {
// Last song, just reset currentPosition
currentPosition = 0;
// playSong(MEDIA_PATH + songs.get(currentPosition));
} else {
// Play next song
playSong(MEDIA_PATH + songs.get(currentPosition));
}
}
private void demoPause(){
mp.pause();
playerButton.setText(R.string.play_label);
Toast.makeText(this, notPlaying, Toast.LENGTH_LONG).show();
Log.d(TAG, notPlaying);
}
// Initiate playing the media player
private void demoPlay(){
mp.start();
playerButton.setText(R.string.stop_label);
Toast.makeText(this, isPlaying, Toast.LENGTH_LONG).show();
Log.d(TAG, isPlaying);
}
// Toggle between the play and pause
private void playPause() {
if(mp.isPlaying()) {
demoPause();
} else {
demoPlay();
}
}
}

Categories

Resources