How to stop a MediaPlayer using a button - java

The code I have so far is:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void SoundPlayer(View view) {
MediaPlayer soundMediaPlayer1 = MediaPlayer.create(this, R.raw.gun_sound);
soundMediaPlayer1.start();
}
public void DogSound(View view) {
MediaPlayer soundMediaPlayer2 = MediaPlayer.create(this, R.raw.cat_sound);
soundMediaPlayer2.start();
}
public void NewSound(View view) {
MediaPlayer soundMediaPlayer3 = MediaPlayer.create(this, R.raw.new_sound);
soundMediaPlayer3.start();
}
public void LaughTrack(View view) {
MediaPlayer soundMediaPlayer12 = MediaPlayer.create(this, R.raw.laugh_sound);
soundMediaPlayer12.start();
}
public void HorseSound(View view) {
MediaPlayer soundMediaPlayer4 = MediaPlayer.create(this, R.raw.horse_sound);
soundMediaPlayer4.start();
}
public void HeySound(View view) {
MediaPlayer soundMediaPlayer5 = MediaPlayer.create(this, R.raw.hey_sound);
soundMediaPlayer5.start();
}
private void Stop() {
startActivity(new Intent(this, MainActivity.class));
}
public void stop(View view) {
Stop();
}
}
The problem I face is that all the sounds overlaps and plays. I have a STOP button set up, but have no idea has to how to make it stops the media. Any feedback is helpful.
Thank you.

First of all, I would use only one Instance of the MediaPlayer. You can then use mediaPlayer.stop() to stop a sound and prepare the next one.
See the state diagram on https://developer.android.com/reference/android/media/MediaPlayer.html

1) Make the object of MediaPlayer in onCreate method don't create in every new method.
2) Before playing the music in another method first use stop() function to stop current playing sound(like mediaPlayer.stop(); ) then play the sound by start().

Related

Android Studio Soundboard buttons won't play sound after switching activity i can press them only like 7 times before they stop

In Android studios i made Soundboard in which i have 4 activities when i'm on first activity i can press sounds all day and they play but right after i click next for second activity when i try to play them they won't play sound. I can click like 7 times and they stop.
I look everywhere but nothing works i even changed whole code again still same thing happens.
Button button1;
Button theuniverserequired, iusedthestones, etc more sounds....
iaminevitable = (Button) findViewById(R.id.iaminevitable);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.iaminevitable);
iaminevitable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mp.start();
}
});
iusedthestones = (Button) findViewById(R.id.iusedthestones);
final MediaPlayer mp2 = MediaPlayer.create(this,
R.raw.iusedthestones);
iusedthestones.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mp2.start();
}
}); etc....
button1 = findViewById(R.id.button_1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent int1 = new Intent(MainActivity.this, Activity2.class);
startActivity(int1);
}
});
there is nothing in error messages for why is this happening
First off: Declare your MPs outside your onCreate to prevent it from garbage collected when activity is paused
private MediaPlayer mp,mp2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mp = new MediaPlayer.create(...
mp2 = new MediaPlayer.create(...
Further more: Drop off resources used by MPs when activity stops to avoid memory leaks which may force your app to crash on continuous usage.
#Override
protected void onStop() {
super.onStop();
if (mp != null) {
mp.reset();
mp.release();
mp = null;
}
if (mp2 != null) {
mp2.reset();
mp2.release();
mp2 = null;
}
}

My android App stop playing sound on button tap after some time

Hello there, i have just created a basic android app which plays different musics on button tap..
The app just worked fine for the first couple of seconds but when i just keep on tapping and tapping , at some point it stops playing the music and just crashed...
I am unable to figure out what the problem is ..Please help me make it work..
Thanks.
Here is my code :-
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
public void PlayMusic(View view)
{
int ID = view.getId();
String NameID = view.getResources().getResourceEntryName(ID);
int sound= getResources().getIdentifier(NameID,"raw","com.example.pickachu.mypatatap");
mediaPlayer = MediaPlayer.create(this,sound);
mediaPlayer.start();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
The sound is not playing after multiple taps because you must be getting IllegalStateException because you are not releasing the Mediaplayer object and Mediaplayer Lifecycles are not managed properly when you tap multiple times.
You can use setOnCompletionListener(MediaPlayer.OnCompletionListener listener) to release mediaPlayer after completion of sound as:
mediaPlayer = MediaPlayer.create(this,sound);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.reset();
mp.release();
mediaplayer = null;
}
});
mediaPlayer.start();
pass uri instead string
mediaPlayer= MediaPlayer.create(this, Uri.parse(Environment.getExternalStorageDirectory().getPath()+ "/Music/music.mp3"));
mediaPlayer.setLooping(true);
mpintro.start();

How can I not have to wait for the MediaPlayer to finish in Android Studio?

I'm currently using a MediaPlayer to play a 1 second sound file. However, I can't replay it right afterwards; I have to wait a while, which I don't want to do.
I want to be able to play the sound file right after I click the View.
Here's my code:
final TextView lowBongo = (TextView)this.findViewById(R.id.low_bongo);
final MediaPlayer lowBongoMP = MediaPlayer.create(this, R.raw.low_bongo_sound);
lowBongo.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
lowBongoMP.start();
}
});
final TextView lowBongo = (TextView)this.findViewById(R.id.low_bongo);
final MediaPlayer lowBongoMP = MediaPlayer.create(this, R.raw.low_bongo_sound);
lowBongo.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
lowBongoMP.seekTo(0); //Start Song From 0 second
lowBongoMP.start();
}
});
Stop whenever the song is about to play
final TextView lowBongo = (TextView)this.findViewById(R.id.low_bongo);
final MediaPlayer lowBongoMP = MediaPlayer.create(this, R.raw.low_bongo_sound);
lowBongo.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
lowBongoMP.stop(); //stop current song
lowBongoMP.start();
}
});

Android MediaPlayer start called in State 1. Error -38,0

Good day! As usual - I am starting to learn Android programming and have faced unexpected difficulty while trying to create basic MediaPlayer app. Audio file is stored in res/raw. It is accessed with create(). I have read a few manuals on how to build a media player app and was convinced that using prepare() and prepareAsync() was not necessary in case if file is stored in res/raw folder. So here is my initial code
private MediaPlayer playerM = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button playButton = (Button) findViewById(R.id.playButton);
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playMusic(R.raw.sleep_away);
}
});
Button stopButton = (Button) findViewById(R.id.pauseButton);
stopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopMusic();
}
});
}
private void playMusic(int rid) {
playerM.create(this, rid);
playerM.start();
}
private void stopMusic() {
playerM.stop();
}
}
Since that I have made numerous changes, but nothing helped. According to dev.android manual on MediaPlayer the code above should work. However it results in the following errors:
E/MediaPlayer: start called in state 1, mPlayer(0x0)
E/MediaPlayer: error (-38, 0)
E/MediaPlayer: Error (-38,0)
Probably I am just making some blunt mistake. Any help would be much appreciated.
Solved by myself
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
Uri myUri = Uri.parse("android.resource://" + v.getContext().getPackageName() + "/" + R.raw.sleep_away);
System.out.println(myUri);
playerM.setDataSource(v.getContext(), myUri);
playerM.prepare();
playerM.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer playerM){
playerM.start();
}
});
}catch(IOException e){
e.printStackTrace();
}
}
});
I know I should add other methods to change State, but the main purpose was to get it to play file.

How to turn off music bgm(Background Music) from other java

I am making an app where bgm start from main page. But I couldn't find a way to turn it off when starts learning.
Can I remotely switch off bgm from different java file
This is my 1st java,mainmenu.class
public class mainmenu extends AppCompatActivity {
MediaPlayer bkgrdmsc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenu);
Button btn = (Button) findViewById(R.id.mula);
assert btn != null;
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ke_belajar_latihan = new Intent(getApplicationContext(), taqi.mengaji.belajar_latihan.class);
startActivity(ke_belajar_latihan);
}
});
bkgrdmsc = MediaPlayer.create(this, R.raw.song);
bkgrdmsc.setLooping(true);
bkgrdmsc.start();
}
}
This is the other file I want to remotely off the bgm when starting the learning session(as student start to learn)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.belajar_hija_baris);
Button btn=(Button) findViewById(R.id.hijaiyyah);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ke_hijaiyah=new Intent(getApplicationContext(),taqi.mengaji.hijaiyyah.class);
startActivity(ke_hijaiyah);
}
});
}
I want R.id.hijaiyyah to navigate to learn xml also stop bgm
Please help I'm a newbie XD
Make an singleton class and add you music playing code into it for stopping and starting and use that singleton class in all your 2 activities for eg:
public class MusicManager {
private static MusicManager refrence = null;
public static MusicManager getInstance(){
if(refrence == null){
refrence = new MusicManager ();
}
return refrence;
}
}
Add a public method to this singleton class to start and stop music
public void initalizeMediaPlayer(Context context, int musicId){
// add initalization of media player in it and loop it
MediaPlayer bkgrdmsc;
bkgrdmsc = MediaPlayer.create(this, R.raw.song);
bkgrdmsc.setLooping(true);
}
public void startPlaying(){
bkgrdmsc.start();
}
public void stopPlaying(){
bkgrdmsc.stop();
}
//Add stuff like pausing and resuming if you desire
To use this class add this to any activity you want to play music:
MusicManager.getInstance().initalizeMediaPlayer(this, R.raw.menu); // to initalize of media player
MusicManager.getInstance().startPlaying();// to start playing music
MusicManager.getInstance().stopPlaying(); // to stop playing music
You can also use service to perform this task as service runs in background. You can start and stop service any time in your code.

Categories