Play an Audio File in on Button Click Android Appliction

  1. package com.example.lucifer.myapplication;  
  2. import android.app.Activity;  
  3. import android.content.res.AssetFileDescriptor;  
  4. import android.media.MediaPlayer;  
  5. import android.os.Bundle;  
  6. import android.view.View;  
  7. import android.widget.Button;  
  8. import java.io.IOException;  
  9. public class MainActivity extends Activity  
  10. {  
  11.     public Button b;@  
  12.     Override  
  13.     protected void onCreate(Bundle savedInstanceState)  
  14.     {  
  15.         super.onCreate(savedInstanceState);  
  16.         setContentView(R.layout.activity_main);  
  17.         final MediaPlayer mp = new MediaPlayer();  
  18.         Button b = (Button) findViewById(R.id.button_sound);  
  19.         b.setOnClickListener(new View.OnClickListener()  
  20.         {@  
  21.             Override  
  22.             public void onClick(View v)  
  23.             {  
  24.                 if (mp.isPlaying())  
  25.                 {  
  26.                     mp.stop();  
  27.                 }  
  28.                 try  
  29.                 {  
  30.                     mp.reset();  
  31.                     AssetFileDescriptor afd;  
  32.                     afd = getAssets().openFd("myaudio.mp3");  
  33.                     mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());  
  34.                     mp.prepare();  
  35.                     mp.start();  
  36.                 }  
  37.                 catch (IllegalStateException e)  
  38.                 {  
  39.                     e.printStackTrace();  
  40.                 }  
  41.                 catch (IOException e)  
  42.                 {  
  43.                     e.printStackTrace();  
  44.                 }  
  45.             }  
  46.         });  
  47.     }  
  48. }  
  49. "activity_main.xml"  
  50. file - < LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"  
  51. android: id = "@+id/layout_login"  
  52. android: layout_width = "fill_parent"  
  53. android: layout_height = "wrap_content"  
  54. android: orientation = "vertical"  
  55. android: layout_gravity = "top" > < Button  
  56. android: id = "@+id/button_sound"  
  57. android: layout_gravity = "center"  
  58. android: layout_width = "wrap_content"  
  59. android: layout_height = "wrap_content"  
  60. android: layout_marginLeft = "150dp"  
  61. android: text = "Click me for sound" / > < /LinearLayout>