Tuesday, April 5, 2016

Play Audio with Media API in Android

"Jai Saraswati Maa"

Hi ... Dear All ..Today I am uploading a superb example of playing Audio using Media API.
In this example i played a Audio from sdcard/Music folder.
Please check.
I am using Android Studio 1.5.1
Minimun SDK API 19 
Target SDK API 23
Please Like us & put your valuable suggestions in comment box.
Please check on Real Device on emulator it will not enjoyable as compare to physical device.****** Please add permissions in manifest file ************


<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE">

</uses-permission>

*** I have added raw folder under res and put a mp3 in this folder.
*** I also put in comment to play your default ringtone
*** I also added your sdcard path check carefully comment lines

A. Nothing added in layout file default activity_main.xml file so 
     i am ont uploading this.

B. Java Code 

package com.exam.ravi.audioex1;

import android.media.MediaPlayer;
import android.os.Environment;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
      MediaPlayer mp=new MediaPlayer();
       try{
            //mp.setDataSource("/sdcard/Music/msw.mp3");

            mp.setDataSource(Environment.getExternalStorageDirectory().getPath()+
               "/Music/msw.mp3");
            mp.prepare();
            mp.start();

        }catch(Exception e){e.printStackTrace();}

   //MediaPlayer mp = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);

        //MediaPlayer mp = MediaPlayer.create(this, R.raw.laugh);

        //mp.start();    }
}

No comments:

Post a Comment