Android: if statement not working with .isPlaying() - java

I created an onClick methord PlaySound in which an if statement checks weather the sound is playing or not , if it is playing it stops it or else it starts it.The problem i face is that the if statement is always false and never true.
CODE
public void PlaySound(View view) {
final MediaPlayer clickSound = MediaPlayer.create(this, R.raw.abcd);
if(clickSound.isPlaying()) {
clickSound.stop();
}
else{
clickSound.setLooping(true);
clickSound.start();
}
}

Remove
final MediaPlayer clickSound = MediaPlayer.create(this, R.raw.abcd);
from play method and create it outside of the method.
Edit for your convenince follow the steps:
You can take a global variable of MediaPlayer
public MediaPlayer clickSound ;
and then create in onCreate method:
clickSound = MediaPlayer.create(this, R.raw.abcd);
and thus your play method will be:
public void PlaySound(View view) {
if(clickSound.isPlaying()) {
clickSound.stop();
}
else{
clickSound.setLooping(true);
clickSound.start();
}
}

Related

Adding music in android studio (java, MediaPlayer)

buttonMusic = findViewById(R.id.buttonMus);
musicSound = MediaPlayer.create(this, R.raw.music);
buttonClick();
}
private Button buttonMusic;
private MediaPlayer musicSound;
public void buttonClick() {
buttonMusic.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
soundPlay(musicSound);
}
}
);
}
public void soundPlay(MediaPlayer sound) {
if (sound.isPlaying()) {
sound.stop();
}else {
sound.start();
sound.setLooping(true);
} }
Hello.
The code launches the music, is able to stop it, but it wont play again after pressing the play button, after pausing the song that is.
you aren't pausing song, you are stop()ing it. use sound.pause() for pausing :)
after stop() MediaPlayer you have to prepare it again, use prepare() or prepareAsync(). MediaPlayer.create( makes that for you at the beginning, also if you would create MediaPlayer using its constructor you would also want to prepare()/preapreAsync() before calling start() in onClick
check out state diagram of MediaPlayer

Android - how to get resource by button tag?

I have 8 buttons in my Activity and 8 small audios in the res/raw directory. When one button is clicked, the app plays the audio associated with that particular button. I named each audio the same / similar to the associated button's tag. I want to have only one method in my activity that solves all cases.
This is what I have so far :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void playPhrase(View view){
if(view.getTag().toString().equals("doYouSpeak")){
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.doyouspeakenglish);
mediaPlayer.start();
}
else if(view.getTag().toString().equals("goodEvening")){
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.goodevening);
mediaPlayer.start();
}
// the other 6 cases
}
}
Is there a way to access the audios using the associated button tag (or id or anyhow) without the whole if/else statements ? Something like :
public void playPhrase(View view){
String tag = view.getTag().toString();
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.tag);
mediaPlayer.start();
}
You can use getIdentifier() method to get the id by String name.
String tag = view.getTag().toString();
Int id = getResources().getIdentifier(tag, "raw", getPackageName());
MediaPlayer mediaPlayer = MediaPlayer.create(this, id);
mediaPlayer.start();

Play and pause Mediaplayer with variable

I'm trying to build an Android App where the user can play audiofiles labeled with an id from a database.
//get id from database and turn it into a string, add letter a, because its a res file
stringId = "a" + String.valueOf(standard.getId());
//find playbutton
final FloatingActionButton play = (FloatingActionButton) findViewById(R.id.play);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//to be able to feed mediaplayer a variable I put it in another function called playAudio
playAudio(stringId, true); }
});
final FloatingActionButton pause = (FloatingActionButton) findViewById(R.id.pause);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
playAudio(stringId, false); }
});
The playAudio looks like this:
private void playAudio(String nameOfFile, Boolean booleanPlay){
MediaPlayer mediaPlayer = MediaPlayer.create(this, getResources().getIdentifier(nameOfFile, "raw", getPackageName()));
if (booleanPlay = true){
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
}
if (booleanPlay = false){
mediaPlayer.pause();
}
}
When I run my code every time I press play it creates a new mediaplayer which starts playing at the same time as the other mediaplayer, the pause button doesn't work for the same reason. I can't figure out how to make it work.
Do not create a new MediaPlayer instance each time you play a new file. Create an instance at the beginning and reuse it:
private static MediaPlayer mediaPlayer = new MediaPlayer ();
When changing the file to play, try this piece of code:
AssetFileDescriptor afd = getApplicationContext ().getResources ().openRawResourceFd (R.raw.sound);
if (afd != null)
{
mediaPlayer.reset()
mediaPlayer.setDataSource(afd.getFileDescriptor (), afd.getStartOffset (), afd.getLength ());
mediaPlayer.setLooping (true);
mediaPlayer.prepare ();
mediaPlayer.start ();
}
Replace R.raw.sound with the filename of the sound to play (this would be in the res/raw folder) or use a different way to reference the file as needed.
That works for me -- tested on Android 8.1 (targeted). Hope this helps.
EDITED TO ADD: I just noticed you have wrong operators in the if(booleanPlay = false) and if (booleanPlay = true) statements. They should be == (comparison, instead of assignment).
And one last thing: When exiting, you should call mediaPlayer.release() to free up the resources, but you probably knew that. Glad I could help.

android app crashes when starting/stopping media

I am writing a small practice app that plays a sound clip when a button is tapped. In my previous code, this amounts to just the creation of a MediaPlayer object and a call to mp.start() to start the audio.
This works, but now I would like that same button to play only when no sound is playing yet. If sound is playing, stop the audio. A play/stop button.
I tried to do this using the following code:
```
public class MainActivity extends Activity {
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void goButtonClicked(View v) {
if(mp == null) {
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.wordt);
}
if(mp.isPlaying()) {
mp.stop();
mp.release();
}
else {
mp.start();
}
}
}
```
However now when I run the app, the app crashes when I tap the button. Where did I go wrong?
Just change your code like this,
public void goButtonClicked(View v) {
if(mp == null) {
mp = MediaPlayer.create(getApplicationContext(), R.raw.wordt);
}
....
}
What happens here is, MediaPlayer mp = ... means you are creating a local variable inside if condition. But still your field variable is null. And when the app executes the second if condition, it throws a NullPointerException.
You didn't initialize your first mp object, so you see nullPointerException,
and you can delete second mp object

multiple mediaplayer sound crash android

I have multiple sounds i would like loaded
final MediaPlayer mp = MediaPlayer.create(this, R.raw.testsnd);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.testsnd2);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.testsnd3);
ect.
I have sound starts within clicklisteners
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp.start();
}};
It has to be final as mp.start(); won't be seen within listeners
Is there a way to switch between the different sounds as mediaplayer will crash the app
if I use this more than once
Can set tag/ get tag be used if possible to make the switch?
Please help!
The MediaPlayer has a state machine that I believe you are ignoring. The static create methods are a shortcut for one-time deals. If you want the MediaPlayer to be used more than once, do something like this:
final MediaPlayer mp1 = new MediaPlayer();
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick() {
try {
mp1.reset();
mp1.setDataSource(YourClass.this,
Uri.parse("android.resource://com.your.package/" + R.raw.testsnd);
mp1.prepare();
mp1.start();
}
catch (Exception ex) {
// handle error
}
}
}
It should be trivial to replace your package and class names, and also to extrapolate the idea for multiple MediaPlayers. Chances are you only need one at any given time unless the sounds can be played at the same time. Also, don't forget to call release() when you are done.
If the sounds are brief, you may want to look into using SoundPool also.
I can`t understand why you do things like that, can you post more of your code? But if you need to play three sounds from your MediaPlayer instance you can try this:
private final MediaPlayer mpSound1;
private final MediaPlayer mpSound2;
private final MediaPlayer mpSound3;
private void playSound1(){
try{
if(mpSound1==null)
mpSound1 = MediaPlayer.create(this, R.raw.testsnd);
mpSound1.start();
}catch(Exception ex){
mpSound1 = null;
}
}
private void playSound2(){
try{
if(mpSound2==null)
mpSound2 = MediaPlayer.create(this, R.raw.testsnd2);
mpSound2.start();
}catch(Exception ex){
mpSound2 = null;
}
}
private void playSound3(){
try{
if(mpSound3==null)
mpSound3 = MediaPlayer.create(this, R.raw.testsnd3);
mpSound3.start();
}catch(Exception ex){
mpSound3 = null;
}
}

Categories

Resources