stopping the music and playing it again - java

I tried to make a small music file reader project , I used the code below sow i can play the music and pause it but once I stop it and click on a button to play it from the begining the music is not played
I used the code below and I don t know how to solve that problem :
final MediaPlayer mp=new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mp.setDataSource(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) +String.valueOf("/myfile.mp3"));
} catch (IOException e) {
e.printStackTrace();
}
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!mp.isPlaying()){
try{
mp.prepare();
}catch(Exception e){e.printStackTrace();}
mp.start();
btn1.setText("pause");
}else{
mp.pause();
btn1.setText("play");
}
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
mp.reset();
btn2.setVisibility(btn2.INVISIBLE);
btn1.setText("play");
}
});
}

Option 1 : you can go back from the beginning with mp.seekTo(0); after calling mp.stop(); also remove the mp.reset(); like this:
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
mp.seekTo(0);
btn2.setVisibility(btn2.INVISIBLE);
btn1.setText("play");
}
});
Option 2 : When calling mp.reset(); you are restoring the object into it's Idle state that's why the music cannot be played. You have to transfer the object into the Initialized state by calling mp.setResource(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) +String.valueOf("/myfile.mp3")); and then mp.prepare(); like this:
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
mp.reset();
btn2.setResource(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) +String.valueOf("/myfile.mp3"));
mp.prepare();
btn1.setText("play");
}
});
I suggest that you go for Option 1
I hope this helps. I haven't done any android programming but I know some Java and read the details about the MediaPlayer right here.

From the state machine of the documentation, it seems that you have to use
mp.stop()
mp.prepare()
mp.start()
This would complete the state machine.

Add these lines of code in your btn2 onClick
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
mp.reset();
btn2.setVisibility(btn2.INVISIBLE);
btn1.setText("play");
mp=new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mp.setDataSource(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) +String.valueOf("/myfile.mp3"));
} catch (IOException e) {
e.printStackTrace();
}
}
});
It will repair the media player to play again after you reset it.
This is my code implemented as you desired except I am loading music from RAW folder
public class MainActivity extends AppCompatActivity {
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button stopButton = (Button) findViewById(R.id.button_stop);
final Button playButton = (Button) findViewById(R.id.button_play);
mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.file);
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!mediaPlayer.isPlaying()){
mediaPlayer.start();
playButton.setText("pause");
stopButton.setVisibility(View.VISIBLE);
}else{
mediaPlayer.pause();
playButton.setText("play");
}
}
});
stopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.reset();
stopButton.setVisibility(INVISIBLE);
playButton.setText("play");
mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.file);
}
});
}
}

Related

How to terminate music using back button of phone and created back button?

I was having some bugs with playing a music in my app. It wont stop playing even if I exit the app. It will only stop if I hit pause or terminate the app. Here's my code for music. What should I do code to stop it.
public void play_brain(View g){
final MediaPlayer brainMP = new MediaPlayer();
try {
brainMP.setDataSource("https://firebasestorage.googleapis.com/v0/b/capstone-katugna-001.appspot.com/o/meditation%20music%201%20minute%20peaceful%20music%201%20minute%20mindfulness%20meditation%201%20minute%20relax%20music%201.mp3?alt=media&token=f34fe7c7-54f1-4645-88cf-5e7a21f401d8");
brainMP.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
brainMP.prepare();
} catch (IOException e) {
e.printStackTrace();
}
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
brainMP.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.pause();
}
});
brainMP.pause();
}
});
}
You can try using this code:
public class MainActivity extends AppCompatActivity {
private MediaPlayer mediaPlayer;
private Button buttonStartPause;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// Initialize your MediaPlayer object here
Uri myUri = ....; // initialize Uri here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(getApplicationContext(), myUri);
mediaPlayer.prepare();
}
buttonStartPause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mediaplayer.isPlaying()) {
mediaplayer.pause();
// here you can set the play icon to your button
} else {
mediaplayer.start();
// here you can set the pause icon to your button
}
}
});
// To capture back button's pression you can override onBackPressed() in your Activity:
#Override
public void onBackPressed() {
if (mediaplayer.isPlaying()) {
mediaplayer.pause();
}
super.onBackPressed();
}
}

Stop audio playing on backpress

I have an activity when i click on play button and it plays mp3 sound. When I click back the audio still plays in the background and can also run alongside other audio sounds which is annoying. I have tried to implement other methods used on here but to no avail.
Code:
public class InstructionsManualActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_instructions_manual);
Button one = (Button) this.findViewById(R.id.instructionsManual_but);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.instructions_manual);
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp.start();
}
});
}
}
I have tried this code but app crashes on back press
#Override
public void onBackPressed() {
super.onBackPressed();
if (mp.isPlaying()) {
mp.stop(); // or mp.pause();
mp.release();
First of all declare the MediaPlayer object Globally
MediaPlayer mp = null; //Declaring globally so can access anywhere in activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_instructions_manual);
Button one = (Button) this.findViewById(R.id.instructionsManual_but);
mp = MediaPlayer.create(this, R.raw.instructions_manual);
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp.start();
}
});
}
When you are pressing back button in any activity onBackPressed()
will be called , there you can stop you media player if playing.
#Override
public void onBackPressed() {
super.onBackPressed();
//Here you can stop your MediaPlayer
if (mp != null && mp.isPlaying()) {
mp.stop();
mp.release();
}
}
Try this it's working for me
if (mp != null) {
mp.stop();
mp.release();
mp = null;
finish();
}
Your code is fine just check it before stop for null player
super.onBackPressed();
if (mp!=null && mp.isPlaying()) {
mp.stop(); // or mp.pause();
mp.release();

Why I am having error after I click my image button many times

When I click the image button for more than 15 times it should stop functioning. What is the code that I can use here?
I am new developer and I really need your help. I hope you can help me
here is my code:
public class MainActivity extends Activity{
MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
ImageButton One = (ImageButton) findViewById(R.id.btnkick);
One.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.kick1);
try
{
mp.prepare();
}
catch (IOException e)
{}
catch (IllegalStateException e)
{}
mp.start();
}
});
ImageButton two = (ImageButton) findViewById(R.id.btnkick1);
two.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.kick1);
try
{
mp.prepare();
}
catch (IOException e)
{}
catch (IllegalStateException e)
{}
mp.start();
}
});
int count=0;
One.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
count=count+1;
if(count<=15)
{
MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.kick1);
try
{
mp.prepare();
}
catch (Exception e)
{
e.printStackTrace();
}
mp.start();
}
}
});
int counttwo=0;
two.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
counttwo=counttwo+1;
if(counttwo<=15)
{
MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.kick1);
try
{
mp.prepare();
}
catch (Exception e)
{
e.printStackTrace();
}
mp.start();
}
}
});
use this in your code.

How to set duration time to play song in Android?

I have song which duration is 15min. But I would like to play this song for 30 minutes. Also when the user will download PRO version of the application, the song should play for 2 hours. How can I set the time?
I am new to Java and Android.
Thanks for your help.
public class MainActivity extends Activity {
Button start, stop;
// Button btn_play, btn_stop, btn_pause;
MediaPlayer mp;
TextView display, comment;
int length;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
length = 0;
start = (Button) findViewById(R.id.bStart);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp = MediaPlayer.create(MainActivity.this, R.raw.splahsound);
mp.seekTo(length);
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.stop();
mp.reset();
mp.release(); // free up memory
mp = null;
length = 0;
}
});
}
});
stop = (Button) findViewById(R.id.bDur);
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp != null) {
try {
mp.stop();
mp.reset();
mp.release();
mp = null;
length = 0;
} catch (Exception e) {
Log.d("error", e.toString());
}
}
}
});
}
}
Use TimerTask. A similar question has already been answered here, so pointing to that.

How to stop already playing sound and immediately start another

When a sound that the user previously selected is playing, how can I stop that sound and immediately play the new selected sound? The code I have so far only stops the new sound, but the user has to select the sound again in order to play it.
public class MainActivity extends Activity {
public MediaPlayer mediaPlayer = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button a = (Button) findViewById(R.id.First);
a.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.firstsound);
mediaPlayer.stop();
}
else {
mediaPlayer.start();
mediaPlayer = null;
}
}
}
);
Button b = (Button) findViewById(R.id.Second);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.secondsound);
mediaPlayer.stop();
}
else {
mediaPlayer.start();
mediaPlayer = null;
}
}
}
);
I am making a soundboard with over 30 sounds, if that helps at all. What (slight I assume) changes would I need to make to my code? Any help would be greatly appreciated!
public class MainActivity extends Activity {
public MediaPlayer mediaPlayer = null;
public Boolean playing=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button a = (Button) findViewById(R.id.First);
a.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
(playing)mediaPlayer.stop();
mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.firstsound);
mediaPlayer.start();
playing=true;
}
});
Button b = (Button) findViewById(R.id.Second);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
(playing)mediaPlayer.stop();
mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.firstsound);
mediaPlayer.start();
playing=true;
}
});
}
}

Categories