HOW TO ADD SOUND OR MUSIC TO YOU ANDROID STUDIO PROJECT

  1. create a new Directory under the res folder and name it raw
  2. add your desired music or sound to the raw folder
  3. in you MainActivity.java put the code below

package com.example.sound;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
    MediaPlayer answerPlayer;
    private static final String SOUND = "Sound";
    private static final String MyPref = "MyPref";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = findViewById(R.id.play);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                speak(R.raw.coin);
            }
        });
    }
    public static boolean getSound(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(MyPref, Context.MODE_PRIVATE);
        return sharedPreferences.getBoolean(SOUND, true);
    }
    public void speak(int sound) {
        if (getSound(getApplicationContext())) {
            if (answerPlayer != null) {
                answerPlayer.release();
            }
            answerPlayer = MediaPlayer.create(getApplicationContext(), sound);
            if (answerPlayer != null) {
                answerPlayer.start();
            }
        }
    }
}
  1. Add the below code to your main_activity.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:gravity="center"
    tools:context=".MainActivity">
   <Button
       android:id="@+id/play"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Play"
       />
</LinearLayout>

Your android studio should look like the one below

sound1.png