Easy tutorial how to play your sound from pc, offline, in Android Studio, using MediaPlayer.

Create new project with Application name: Play sound; Minimum SDK: API 21Android 5 (Lollipop).

In app->res->layout-> create New Directory: raw and copy-paste a sound from your computer, with name: sound.mp3.

In app->res->layout->activity_main.xml write the code:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
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"
tools:context=".MainActivity">
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

In app->res->values->strings.xml write the code:

<resources>
<string name="app_name">Play sound</string>
<string name="button">Play Sound</string>
</resources>

In app->java->MainActivity.java write the code:

package com.app.toyo.playsound;
import android.content.Context;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
    Context context = this;
    MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
        mp = MediaPlayer.create(context, R.raw.sound);
        final Button b = (Button) findViewById(R.id.button);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (mp.isPlaying()) {
                        mp.stop();
                        mp.release();
                        mp = MediaPlayer.create(context, R.raw.sound);
                    }
                    mp.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
}
}

Run app in mobile device or Emulator (API 27 Android 8.1) and watch your video in format portrait or landscape.

Follow YouTube Video Tutorial:

 

Download project with Source Code from here:
http://android-coffee.com/wp-content/uploads/projecs/Playsound.7z

Please subscribe here to our YouTube channel. Thank you!
Check next tutorials to learn all about Android.
For further questions leave a message.

Leave a Reply

Your email address will not be published. Required fields are marked *

Blue Captcha Image Refresh

*