Playing a downloaded song - android

I'm new to android so I'm having a problem thinking of a solution. First thing I do is change activities to a different screen, and while in the activity I download a song. I then return to MainActivity which is a MediaPlayer activity. Now, I'm a little confused on activity lifecycles, if I return to MainActivity, and run:
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
File song = new File(path, "SpaceJam.mp3");
That's in my onCreate, so basically I'm asking does onCreate run every time you return to an activity?
Second, I have a play/pause button:
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// check for already playing
if(mp.isPlaying()){
if(mp!=null){
mp.pause();
// Changing button image to play button
btnPlay.setImageResource(R.drawable.play_t); }
}else{
// Resume song
if(mp!=null){
mp.start();
// Changing button image to pause button
btnPlay.setImageResource(R.drawable.pause_t);
}
}
}
});
The problem is, I don't want to do use:
mp.setDataSource(path+"/"+fileName);
mp.prepare();
mp.start();
On my play button, because it'll reinitialize the song every time. What's the best way to go about doing this?
Thanks

That's in my onCreate, so basically I'm asking does onCreate run every time you return to an activity?
No. onResume() or onStart() would be good choices but you should read the Activity life cycle documentation and choose accordingly.
http://developer.android.com/training/basics/activity-lifecycle/index.html
On my play button, because it'll reinitialize the song every time. What's the best way to go about doing this?
To save the current position, e.g. in onPause()
Mediaplayer.pause();
length=Mediaplayer.getCurrentPosition();
To resume, e.g. in onResume()
Mediaplayer.seekTo(length);
Mediaplayer.start();

Related

how can stop background runnig process of media player stop when pressed back button of mobile

i am searched many solution but could not find proper result when i press the back button of mobile i am using one counter variable and put the condition like when counter is 0 it called the music file.
but when i am comeout from that activity means press back button of mobile still that activity is runnig and called the music file .i am using this below code for music play.please anyone have solution then help me.i am using one timer function.like this when i==0 that time call one music file but when i press back button. this timer i wants to stop.
public void btntimer(){
new Handler().postDelayed((new Runnable() {
#Override
public void run() {
if(i!=32) {
matchNo();
}
else {
try{
showdialog();
media=1;
}catch (Exception e){
media=0;
}
updatepoints();
}
}
}), 4000);
}
song=MediaPlayer.create(this,R.raw.cartoon1);
song.start();
song.setLooping(false);
If I understand you correct, you want to stop playing music on back button pressed.
Call stop() in onBackPressed method.
#Override
public void onBackPressed() {
song.stop();
song.release();
song = null;
}

Resume MediaPlayer after pressing Home Button

I have a MediaPlayer that streams music in the background, when I press the home button the music stops, which what I want, but when I resume back to the application, the music is not there anymore. And when the current track ends, it doesn't loop.
My code is the following:
MediaPlayer backgroundMusic;
int length = 0;
//play background music
backgroundMusic = MediaPlayer.create(MainActivity.this, R.raw.background_music);
backgroundMusic.start();
backgroundMusic.setLooping(true);
#Override
protected void onPause() {
super.onPause();
if(backgroundMusic.isPlaying()){
backgroundMusic.pause();
length = backgroundMusic.getCurrentPosition();
}else{
return;
}
}
public void onPrepared(MediaPlayer backgroundMusic){
backgroundMusic.start();
backgroundMusic.seekTo(length);
}
How can I resume the music from where it stopped, when I press the Home Button, and Also make the music loop.
Thanks in advance.
Try to implement your code with service class if you want your player to play even in background or if you want to store the position save your data in static variable in onpause and restore it onResume of your Activity.
Preserve position of playing in shared preferences and not in local variable

two media player played at once

i create an app, and in one layout (just call it layout A), i play the media player, then when i went to another layout (just call it Layout B), i want the sound from the Layout A is continue playing in Layout B, and when i went back to the Layout A, i also want the media player is still continuing the music that was played before.
In Layout A, i set this code in onCreate:
player = MediaPlayer.create(this, R.raw.sound);
if(!isMuted())
{
player.setLooping(true);
player.start();
}
...
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
Intent intent = new Intent(A.this, B.class);
stop=1;
startActivity(intent);
}
});
And this code:
#Override
protected void onPause()
{
super.onPause();
if (stop!=1)
{
//stop=1 if i go to another layout, for example when i want to go to Layout B
//if the device is automatically locked, i want the media player is paused and it resumed when i unlock the device, so i use stop!=1 to know whether the sound should be paused or not
player.pause();
length = player.getCurrentPosition();
}
}
#Override
protected void onResume()
{
super.onResume();
if(!isMuted())
{
//isMuted is method to know whether the sound is muted or not, if it isn't muted, then the sound is resumed
player.seekTo(length);
player.setLooping(true);
player.start();
}
}
In layout B, i used this code in onCreate:
player = MediaPlayer.create(this, R.raw.sound);
....
And this code:
protected void onPause()
{
super.onPause();
player.pause();
length = player.getCurrentPosition();
}
#Override
protected void onResume()
{
super.onResume();
if(!isMuted())
{
if(player.isPlaying())
{
}
else
{
player.seekTo(length);
player.setLooping(true);
player.start();
}
}
}
But this is the problem.
When i went to Layout B, the Media Player from Layout A and Media Player from Layout B is played in the same time, so the sound is played simultaneously at one time.
When i went back to the Layout A, the Media Player in Layout B is stopped and the Media Player in Layout A is stopped and played from the beginning again, it didn't continue the Media Player that was played before.
When the device is locked, the media player is still played although i have used the indicator whether is should be paused or not. Any correction to the code?
I would recommend that you use a Service to play and pause/stop your music. It is not recommended to use Activity to handle music that way. You can start a Service and then play music in it. Services run in background and don't get destroyed automatically too often as compared to Activity. Here's a sample app code that does similar to what you need media player sound continue in all activities
In Activity MediaPlayer can play far.
You should use Service to play MediaPlayer and control from anywhere in application.
I used this tutorial.
https://thenewcircle.com/s/post/60/servicesdemo_using_android_service

MediaPlayer force close after consecutive clicks

I've made a button and when you click it, it gives away a short sound(Max one second-sound). But after I've clicked the button about 20 times in a row I get force close..
The code is:
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
MediaPlayer mp = MediaPlayer.create(getBaseContext(), R.raw.buzzer);
mp.start();
}
});
I've tried with mp.stop(); but then my sound stops after it have been played half of the time...
One more thing, does anyone know how to "prepare" the sound when I click? Because the sound gets delayed with some milliseconds the first time I press the button.
Create a MediaPlayer member variable and initialize it in onCreate() the same way you are doing in the listener. Then in the listener just use this code:
if(mPlayer.isPlaying()) {
mPlayer.stop();
}
mPlayer.start();
Then call mPlayer.release() in your finish() Activity. My guess is that since none of your MediaPlayer instances are being released, it's running out of memory to use.
The official document for MediaPlayer is actually incredibly descriptive and helpful:
http://developer.android.com/reference/android/media/MediaPlayer.html

TextView not drawing from within button onClick

I am trying to create a music streaming app.
So far it works just fine.
I am using the
MediaPlayer.create(thisContext, Uri.parse(PATH_TO_STREAM));
convenience method to prepare the infinite stream (24x7 mp3 stream).
It hangs for just a few seconds on this call which I have neatly tucked into my startPlaying() method.
The button doesn't show it's getting clicked until after the stream starts playing so at first the user is left wondering if they tapped the button or missed.
So I want to update a TextView label next to the button that says "Wait..." or "Buffering" etc. then clear it after the stream starts so the user knows they pressed the button OK.
Even if I step through this in debug the label doesn't update until after the onClick is finished. I can comment out the last line that clears the label text and can see it set to "Buffering..." OK. But only after it exits the onClick. Is this a limitation of using the media player create() method?
final Button startbutton = (Button) findViewById(R.id.Button01);
this.tvBuffering = (TextView) findViewById(R.id.tvBuffering);
startbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
tvBuffering.setText("Buffering...");
//do something like invalidate() here??
startPlaying(); //blocks here for a few seconds to buffer then plays.
tvBuffering.setText(" "); //clear the text since it's playing by now.
}
});
It's not such a great idea to intentionally include that sort of delay in the UI, because that will block just about anything the user tries to do for those few seconds. I'm assuming that your startPlaying() includes a call to prepare(), as well as start(). When taking data from a source that won't be immediately available (such as a stream), you should use prepareAsync() instead, which will start preparation and return immediately instead of blocking until preparation is complete.
You can attach a callback to your MediaPlayer to then take action once preparation has completed through a MediaPlayer.OnPreparedListener
Here's a simple example. Note that your OnClickListener can stay the same, as long as you change the prepare() in the startPlaying() method to prepareAsync() and remove the start() call from startPlaying().
startbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
tvBuffering.setText("Buffering...");
startPlaying(); //which should call prepareAsync() instead of prepare()
//and have no call to start()
}
});
mYourMediaPlayer.setOnPreparedListener( new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
start();
tvBuffering.setText(" ");
}
});

Categories

Resources