stop playing sound when another sound is playing in android studio - java

hello I use MediaPlayer for play sound in my project in android studio
when I click in a button and play sound , and when I click in another button that button play another sound , I want the first sound or another sound be stoped and just the last button that I clicked be played
I try this code but it not worked
package azad.broooska.fartfuns;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MusicFartActivity extends AppCompatActivity implements View.OnClickListener {
private CardView cardView1, cardView2, cardView3, cardView4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_fart);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
cardView1 = findViewById(R.id.card_music1);
cardView2 = findViewById(R.id.card_music2);
cardView3 = findViewById(R.id.card_music3);
cardView4 = findViewById(R.id.card_music4);
cardView1.setOnClickListener(this);
cardView2.setOnClickListener(this);
cardView3.setOnClickListener(this);
cardView4.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int id = view.getId();
final MediaPlayer s1 = MediaPlayer.create(this, R.raw.bohemian_fartsody);
final MediaPlayer s2 = MediaPlayer.create(this, R.raw.fart_ballade);
final MediaPlayer s3 = MediaPlayer.create(this, R.raw.fart_uverture);
final MediaPlayer s4 = MediaPlayer.create(this, R.raw.farting_xmas);
if (id == R.id.card_music1) {
s1.start();
s2.stop();
s3.stop();
s4.stop();
} else if (id == R.id.card_music2) {
s2.start();
s1.stop();
s3.stop();
s4.stop();
} else if (id == R.id.card_music3) {
s3.start();
s2.stop();
s1.stop();
s4.stop();
} else {
Toast.makeText(this, "noThing", Toast.LENGTH_SHORT).show();
}
}
}

you are creating new instances of MediaPlayer each time something is clicked and assigning the variables to new objects; make s1,s2... class property;
MediaPlayer s1 ,s2,s3,s4;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_fart);
//some code
s1 = MediaPlayer.create(this, R.raw.bohemian_fartsody);
//assign the rest;
}
public void onClick(View view) {
int id = view.getId();
if (id == R.id.card_music1) {
s1.start();
s2.stop();
s3.stop();
s4.stop();
}
//rest of the code
}

Well, its seems like you don`t want to play very long sounds because you have names like
"fart_ballade" and "fart_uverture" in your code.
If your sounds are not very long it is better to work with the SoundPool class.
The MediaPlayer class sometimes can cause problems if you switch fast between sounds.
So if your sounds are not that long, you can try the SoundPool class.
Here you can learn more about the SoundPool class:
How to use SoundPool
I won`t write any code because SoundPool needs more than 5-6 lines of code to work properly.

Related

Android Studio Java MediaPlayer plays only the first second of audio and then stops

I'm trying to have MediaPlayer play a roughly two minute long mp3 audio, however only the first second is played then the player stops. I've tired both mp3 and wav formats. Here's my code:
package com.pi.audiodemo;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaPlayer mediaPlayer = (MediaPlayer) MediaPlayer.create(this, R.raw.dumb);
mediaPlayer.start();
}
}
You create MediaPlayer within the onCreate function. So it will be deleted right after function returns. Try the following code:
package com.pi.audiodemo;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = (MediaPlayer) MediaPlayer.create(this, R.raw.dumb);
mediaPlayer.start();
}
}

Android: onBackPressed not being recognized

EDIT: Realized and solved the problem on my own. Thank you.
Please bear with me it's actually my first time using Android Studio and Stackoverflow. What I am trying to make is a music player, there are 2 activities. In the second activity when the user taps the play button, the music plays. If the user backs, the music will stop playing and go back to the first activity. Somehow on back pressed is not working. It's grayed out and it tells me that the Method is never used.
package com.radiantminds.radiantminds;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class player1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.mozardpianosonata); //create mediaplayer with song
ImageButton yButton = (ImageButton) findViewById(R.id.imageButton5);
yButton.setOnClickListener(new View.OnClickListener() {
public void onBackPressed(){ //this is not working
if(mp.isPlaying())
{
mp.stop(); // stop music on backpress
}
}
#Override
public void onClick(View view) { //play music on click
if (mp.isPlaying()) {
mp.pause();
} else {
mp.start();
}
}
});
}
}
You have to put it on an Activity, don't forget to call #Override
#Override
public void onBackPressed()
{
super.onBackPressed(); //if you want to do something new remove this line
}
The problem is that you have to place the onBackPressedMethod() outside, as follows :
public class player1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.mozardpianosonata); //create mediaplayer with song
ImageButton yButton = (ImageButton) findViewById(R.id.imageButton5);
yButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) { //play music on click
if (mp.isPlaying()) {
mp.pause();
} else {
mp.start();
}
}
});
}
#Override
public void onBackPressed(){ //this is not working
if(mp.isPlaying())
{
mp.stop(); // stop music on backpress
}
//if you want to do the back action aswell, uncomment the following line
//super.onBackPressed();
}
Make sure the #override is there above the method and you don't declare the method twice.
other alternative is:
onKeyDown()
or add:
super.onBackPressed();
in the method onBackPressed (though i dont suggest it really)

Change action of a button according to text displayed

I would like to know how to change the action of a button according to what text is display in a TextView. I am using Android Studio.
I have tried to use an 'if statement' but that doesn't seem to work. So, I want a different sound to play according yo what text is displayed in the TextView.
package com.msp.exampleapplication;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class PrimaryClass extends AppCompatActivity {
TextView placeholder;
Button playsound_button;
MediaPlayer mySound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.primary_layout);
placeholder = (TextView) findViewById(R.id.placeholder);
playsound_button = (Button) findViewById(R.id.playsound_button);
placeholder.setText(getIntent().getStringExtra("message"));
}
public void playSound(View view) {
if (placeholder.equals("BMW M4")) {
mySound = MediaPlayer.create(this, R.raw.sound);
mySound.start();
}
else if (placeholder.equals("BMW M5")) {
mySound = MediaPlayer.create(this, R.raw.sound2);
mySound.start();
}
}
}
So, if the text of the TextView (placeholder) is "BMW M4", then when the button is clicked, it must play R.raw.sound. And if "BMW M5" is displayed in the TextView (placeholder), then R.id.sound2 must play.
But as I said, I've attempted to use the if statement and when I click the button, no sound plays at all.
Yes, as #Akshay Bhat 'AB' said, you must do this:
if (placeholder.getText().toString().equals("BMW M4")) {
mySound = MediaPlayer.create(this, R.raw.sound);
mySound.start();
}
else if (placeholder.getText().toString().equals("BMW M5")) {
mySound = MediaPlayer.create(this, R.raw.sound2);
mySound.start();
}
Refer this post: how to get text from textview
There's one error in the comment tho, its toString() and not toString
You need to check the text in the TextView and not the reference of the TextView itself.
placeholder.getText().toString().equals("BMW M4")

Random music player onClick Android

So I'm making this Star Wars fan app on Android.
I've got this image of Yoda and a button for him. When you tap it, now he says a sentence (with the mediaplayer).
The thing is, I want him to say different things so I got 4 different MP3 files,but how do I let it choose randomly which one to play when the user clicks on the button?
This is my code for now:
package be.ehb.arnojansens.simpleFrag;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import be.ehb.arnojansens.fragmentexampleii.R;
public class SimpleFragmentActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_fragment);
final Button advice = (Button) findViewById(R.id.YodaAdvice);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.yodamessage);
advice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Hmm Busy I Am", Toast.LENGTH_LONG).show();
mp.start();
}
});
}
}
You can have 4 final messages
final MediaPlayer mp = MediaPlayer.create(this, R.raw.yodamessage);
final MediaPlayer mp1 = MediaPlayer.create(this, R.raw.yodamessage1);//File names would be different I guess
final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.yodamessage2);
final MediaPlayer mp3 = MediaPlayer.create(this, R.raw.yodamessage3);
Also you need a random
Random random=new Random();
And then in your on click method
int r = random.nextInt(4);
if(r==0){
mp.start();
Toast.makeText(getApplicationContext(), "Hmm Busy I Am", Toast.LENGTH_LONG).show();
}
if(r==1){
mp1.start();
Toast.makeText(getApplicationContext(), "I'm hungry", Toast.LENGTH_LONG).show();
}
if(r==2){
mp2.start();
Toast.makeText(getApplicationContext(), "My droid now", Toast.LENGTH_LONG).show();
}
if(r==3){
mp3.start();
Toast.makeText(getApplicationContext(), "Not droid you are looking for", Toast.LENGTH_LONG).show();
}

Android button slow action

I have a button that leads to another page. And whenever I click it I get this info code in logcat :
12-07 16:09:45.073: I/ActivityManager(273): Displayed com.example.prva/.button: +1s764ms
Seconds and ms vary of course each time between 1-3 seconds. The problem is that I noticed that it takes a while for that button to open that page. It has some kind of pause or whatever and this is the only relevant thing I have found in the logcat that could be connected to it. How can I fix this, why is this button acting "slow"?
This is where the button code is :
package com.example.prva;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Meni_Splash extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnv = (Button) findViewById(R.id.buttonv);
btnv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(Meni_Splash.this, button.class));
}
});
}
}
And this is the class that opens :
package com.example.prva;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
public class button extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.button);
//Button click sound
final MediaPlayer MPRadio1 = MediaPlayer.create(this, R.raw.radio1);
final MediaPlayer MPRadio2 = MediaPlayer.create(this, R.raw.radio2);
final MediaPlayer MPRadio3 = MediaPlayer.create(this, R.raw.radio3);
final RadioButton rb1, rb2, rb3;
rb1 = (RadioButton) findViewById(R.id.radio1);
rb2 = (RadioButton) findViewById(R.id.radio2);
rb3 = (RadioButton) findViewById(R.id.radio3);
Button btn = (Button) findViewById(R.id.buttonplay);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(rb1.isChecked())
{
MPRadio1.start();
}
else
{
if(rb2.isChecked())
{
MPRadio2.start();
}
else
{
if(rb3.isChecked())
{
MPRadio3.start();
}
}
}
}
}
);}}
I don't know what thing could make it so slow from these activities?
Your code looks pretty decent to be honest. Not sure entirely what could be causing it to intialise slowly.
But there are two areas to look at.
The first, most likely, is your layout loading:
setContentView(R.layout.button);
I dont imagine your layout to be complex though. But if it is, aka, lots of nested views (linear layouts within other linear layouts), or lots of views (textviews etc) in general on the page, then it could be taking a while to "inflate" the Layout.
Alternatively and less likely, is that MediaPlayer.create takes a fair while to load. The reason I suggest this, is I have no idea how it works, as I've not used it before.
//Button click sound
final MediaPlayer MPRadio1 = MediaPlayer.create(this, R.raw.radio1);
final MediaPlayer MPRadio2 = MediaPlayer.create(this, R.raw.radio2);
final MediaPlayer MPRadio3 = MediaPlayer.create(this, R.raw.radio3);
The best thing to do, would be to profile it with the DDMS profiler. Or put a timer around it, and print the results to logcat.
Also, on a quick note, is it just 2-3 seconds loading? And is it really that bad for what its trying to do?

Categories