MediaPlayer play next track from /res/raw - android

I'm making an lullaby app.Initially there are two tracks in my /res/raw folder.
On completing first track I want it to play next track.
i did this using onCompletionListener.But it is showing force close error.
Below is my code for that.
So can anyone tell me how to do that?
public class PlayRandom extends Activity implements OnCompletionListener{
MediaPlayer mp;
int rnum;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.playrandom);
mp.setOnCompletionListener(this);
mp = MediaPlayer.create(this, R.raw.lullaby1);
mp.start();
}
#Override
public void finish() {
// TODO Auto-generated method stub
super.finish();
mp.stop();
}
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
File pdfFile = new File("res/raw/lullaby2.mp3");
Uri path = Uri.fromFile(pdfFile);
mp.stop();
try{
mp.setDataSource(getApplicationContext(), path);
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I tried this but still its not working.
That meand there's something wrong in OnClickListener.
public class PlayRandom extends Activity implements OnCompletionListener{
MediaPlayer mp;
int rnum;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.playrandom);
mp.setOnCompletionListener(this);
mp = MediaPlayer.create(this, R.raw.lullaby1);
mp.start();
}
#Override
public void finish() {
// TODO Auto-generated method stub
super.finish();
mp.stop();
}
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
Toast.makeText(this,"Yuppieee!!", Toast.LENGTH_SHORT);
}
}

use AssetFileDescriptor for playing file from raw folder:
AssetFileDescriptor afdes = getAssets().openRawResourceFd(R.raw.lullaby2);
mp.reset();
mp.setDataSource(afdes.getFileDescriptor(), afdes.getStartOffset(), afdes.getLength());
mp.prepare();
mp.start();

Related

Seekbar for a mp3 file from SD card

I want add a seekbar on this class , but I cant
Please help me out
public class Play extends Title { // your class name
Button button, button1, stop;
MediaPlayer mp = new MediaPlayer();
/** Called when the activity is first created. */
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.music);
TextView tvHeading = (TextView) findViewById(R.id.titleHeading);
tvHeading.setText("music");
try {
audioPlayer("/sdcard/Android" , "Lala.mp3");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
button = (Button) findViewById(R.id.play);
PersianReshape.ReshapeButton(button, "2 Sfarnaz.TTF", Play.this);
button1 = (Button) findViewById(R.id.puse);
PersianReshape.ReshapeButton(button1, "2 Sfarnaz.TTF", Play.this);
stop = (Button) findViewById(R.id.stop);
PersianReshape.ReshapeButton(stop, "2 Sfarnaz.TTF", Play.this);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mp.start();
}
});
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mp.pause();
}
});
stop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mp.setLooping(true);
}
});
}
public void audioPlayer(String path, String fileName) throws IOException{
if (mp != null) {
mp.reset();
}
try {
mp.setDataSource(path+"/"+fileName);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
//mp.reset();
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
mp.stop();
finish();
}}
I've tried a lot of code but did not receive an answer,
This code reads the file from the memory, but it is not the case for seekbar
PLZ help me

How do I call mediaplayer once only?

In android, I have a mediaplayer on detail screen, which duplicates when I select another screen then play another detail, causing sound files to play on the same time. how do I fix this problem? Id like to play the most recent selected media only.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feeddetail);
tc_recDurat = (TextView)findViewById(R.id.recDetDurat);
tc_recDuratBack = (TextView)findViewById(R.id.recDetDuratBack);
TextView tc_recPath = (TextView)findViewById(R.id.recDetPath);
recPath = (String) intent.getSerializableExtra("INTENT_PATH");
tc_recPath.setText(recPath);
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(recPath);
} catch (IOException e1) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), e1.getLocalizedMessage(), Toast.LENGTH_LONG);
}
ImageButton mClickButton1 = (ImageButton)findViewById(R.id.btnPlay);
mClickButton1.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mediaPlayer !=null){
try {
mediaPlayer
mediaPlayer.prepare();
seekBar.setMax(mediaPlayer.getDuration());
mediaPlayer.start();
seekUpdate();
isPlaying = true;
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
ImageButton mClickButton2 = (ImageButton)findViewById(R.id.btnStop);
mClickButton2.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mediaPlayer.stop();
isPlaying = false;
}
});
I am not sure what your problem is, but i believe you are trying to say that as you change through different activities, the sounds files do not stop playing
In that case you can do the following
In the activity
You can override the onPause method and put mediaPlayer.stop() inside it
#Override
public void onPause() {
super.onPause();
mediaPlayer.stop();
}

Android Media Player Next Song

I have a listview in MainActivity from hehe i passing my listview position using this
Intent intent = new Intent(MainActivity.this, Linkview.class);
intent.putExtra("position", position);
startActivity(intent);
And I have a Linkview class here i received my position using this
final Bundle bundle = getIntent().getExtras();
position = bundle.getInt("position");
And i have a linkArray list.
link = getResources().getStringArray(R.array.lin
My player play well and i can stop it.
But I have a next button
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uri = Uri.parse(link[position+1]);
}
});
When I pressed my next button nothing is happened. I want that when I pressed the next button from my array next link will be play but nothing is play.
How i can solve this issue.
My hole code is here.
public class Linkview extends Activity {
Button play, stop, next;
MediaPlayer mediaPlayer;
private String currentSongIndex;
RowItem rowItem;
MainActivity mainActivity;
Uri uri;
public String link[];
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 0);
setContentView(R.layout.activity_linkview);
stop = (Button) findViewById(R.id.stopbutton);
play = (Button) findViewById(R.id.playbutton);
next = (Button) findViewById(R.id.nextbutton1);
link = getResources().getStringArray(R.array.link);
// String itemString = MainActivity.link[position];
final Bundle bundle = getIntent().getExtras();
// String link = bundle.getString("link");
// position = bundle.getInt("position");
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
if (position <= 2) {
uri = Uri.parse(link[position + 1]);
}
}
});
position = bundle.getInt("position");
uri = Uri.parse(link[position]);
// .parse("android.resource://com.prgguru.example/"
// + R.raw.hosannatamil);");
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(getApplicationContext(), uri);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
}
});
}
protected void onDestroy() {
super.onDestroy();
// TODO Auto-generated method stub
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
}
Maybe this will work:
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
uri = Uri.parse(link[position + 1]);
mediaPlayer.setDataSource(getApplicationContext(), uri);
mediaPlayer.prepare();
mediaPlayer.start();
}
});

Implementing SeekBar in Android in BaseAdapter

In my application I am trying to implement SeekBar.. The SeekBar is working fine when playing the sound at first time. but When I click the button to play the sound again then I am an endless loop of errors regarding the MediaPlayer. The thing that I want is that when I while playing the sound if I click the the play button the sound should play again from the beginning and the SeekBar should also start from beginning. If I remove the the SeekBar then everything is working fine.. But SeekBar is must in my application.. I have implemented all these things in the BaseAdapter.. I have to do all the things in the BaseAdapter. So please help me in letting me the code that works with the BaseAdapter..
This is my code... Please have a look...
mediaPlayer.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(activity, "Loading Message", Toast.LENGTH_LONG).show();
mp.reset();
try {
mp.setDataSource("url for any mp3 audio file");
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.prepareAsync();
mp.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(final MediaPlayer mp) {
// TODO Auto-generated method stub
mp.start();
mediaPlayer.setBackgroundResource(R.drawable.m_pause);
seekBar.setProgress(0);
seekBar.setMax(100);
mUpdateTimeTask = new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
seekBar.setProgress(progress);
mHandler.post(this);
}
});
mUpdateTimeTask.start();
}
});
}
});
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mediaPlayer.setBackgroundResource(R.drawable.m_play);
mp.stop();
try {
mUpdateTimeTask.join();
mHandler.sendEmptyMessage(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mHandler.removeCallbacks(mUpdateTimeTask);
}
});
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onStopTrackingTouch(final SeekBar seekBar) {
// TODO Auto-generated method stub
//mHandler.removeCallbacks(mUpdateTimeTask);
if(mp.isPlaying())
{
int totalDuration = mp.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);
mp.seekTo(currentPosition);
mUpdateTimeTask = new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
//timer.setText(""+utils.milliSecondsToTimer(currentDuration));
seekBar.setProgress(progress);
mHandler.post(this);
}
});
mUpdateTimeTask.start();
}
else
{
seekBar.setProgress(0);
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
if(mp.isPlaying())
{
mHandler.removeCallbacks(mUpdateTimeTask);
}
else
{
seekBar.setProgress(0);
}
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
}
});
mp.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
return false;
}
});
Thanks...
Create a method in your BaseAdapter which sets the current seekbarprogress to zero
void setSeekBarValuetoZero(){
seekBar.setProgress(0);
}
Please check the initially that seekbar is initialized.
You can call this function from yourMediaPlayer class before mp.reset();

Audio streaming stop when screen gets Off in android

I am streaming mp3 on media-player, it plays continuos when your screen is on or you are doing multitasking but when you turn off screen it won't play audio continuously, it stucks many times.And I got this "info/warning (702,0) "on log cat
I tried mp.setWakeMode(getBaseContext(),PowerManager.FULL_WAKE_LOCK);
I am using service to play audio streaming but still it stucks.
public class myPlayService extends Service{
MediaPlayer mp;
String link ="http://85.23.194.72:70/mp3/str";
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
mp = new MediaPlayer();
try {
mp.setDataSource(link);
mp.setWakeMode(getBaseContext(),PowerManager.FULL_WAKE_LOCK);
mp.prepareAsync();
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.start();
}
});
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}#Override public void onDestroy() { mp.stop();mp.release();}}

Categories

Resources