1. Are you ready for the Galaxy S20? Here is everything we know so far!

Playing different sounds on different buttons click

Discussion in 'Android Development' started by xander119, Jan 27, 2020.

  1. xander119

    xander119 Lurker
    Thread Starter

    Hi guys,

    I am new to android and I want to make a simple app for learning purposes.
    So the app should be like this: if I press Button1, it will sing the sound1. If I press Button 2 the sound1 stops and plays sound2.
    Here is what I made so far, but it doesn't work. I tried to search on different websites, but I didn't find anything that could help me so I thought it would be helpful a forum.
    Any help please? :D

    Thank you!

    Code (Java):
    1. package com.example.moan;
    2.  
    3. import androidx.appcompat.app.AppCompatActivity;
    4.  
    5. import android.media.MediaPlayer;
    6. import android.os.Bundle;
    7. import android.view.View;
    8. import android.widget.Button;
    9.  
    10. public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    11.     MediaPlayer cricket;
    12.     @Override
    13.     protected void onCreate(Bundle savedInstanceState) {
    14.         super.onCreate(savedInstanceState);
    15.         setContentView(R.layout.activity_main);
    16.  
    17.  
    18.         Button btnCricket = (Button) this.findViewById(R.id.button);
    19.         btnCricket.setOnClickListener(this);
    20.  
    21.         Button btnCricket2 = (Button) this.findViewById(R.id.button2);
    22.         btnCricket2.setOnClickListener(this);
    23.  
    24.  
    25.  
    26.  
    27.     }
    28.  
    29.     @Override
    30.     public void onClick(View v) {
    31.         switch(v.getId())  {
    32.             case R.id.button:
    33.                 closeCricket();
    34.                 cricket = MediaPlayer.create(this, R.raw.manea1);
    35.                 break;
    36.             case R.id.button2:
    37.                 closeCricket();
    38.                 cricket = MediaPlayer.create(this, R.raw.manea2);
    39.                 break;
    40.             default:
    41.                 return;
    42.         }
    43.  
    44.  
    45.         cricket.start();
    46.  
    47.  
    48.     }
    49.  
    50.     public void closeCricket() {
    51.         if (cricket.isPlaying()) {
    52.             cricket.pause();
    53.             cricket.reset();
    54.             cricket.release();
    55.         } else {
    56.             cricket.reset();
    57.             cricket.release();
    58.         }
    59.  
    60.     }
    61. }
    62.  
     



    1. Download the Forums for Android™ app!


      Download

       
Loading...

Share This Page

Loading...