Skip to main content

Android Media Player Example

We can play and control the audio files in android by the help of MediaPlayer class.
Here, we are going to see a simple example to play the audio file. In the next page, we will see the example to control the audio playback like start, stop, pause etc.

MediaPlayer class

The android.media.MediaPlayer class is used to control the audio or video files.

Methods of MediaPlayer class

There are many methods of MediaPlayer class. Some of them are as follows:
MethodDescription
public void setDataSource(String path)sets the data source (file path or http url) to use.
public void prepare()prepares the player for playback synchronously.
public void start()it starts or resumes the playback.
public void stop()it stops the playback.
public void pause()it pauses the playback.
public boolean isPlaying()checks if media player is playing.
public void seekTo(int millis)seeks to specified time in miliseconds.
public void setLooping(boolean looping)sets the player for looping or non-looping.
public boolean isLooping()checks if the player is looping or non-looping.
public void selectTrack(int index)it selects a track for the specified index.
public int getCurrentPosition()returns the current playback position.
public int getDuration()returns duration of the file.
public void setVolume(float leftVolume,float rightVolume)sets the volume on this player.

Activity class

Let's write the code of to play the audio file. Here, we are going to play maine.mp3 file located inside the sdcard/Music directory.
File: MainActivity.java
  1. package com.example.audiomediaplayer1;  
  2.   
  3. import android.media.MediaPlayer;  
  4. import android.net.Uri;  
  5. import android.os.Bundle;  
  6. import android.app.Activity;  
  7. import android.view.Menu;  
  8. import android.widget.MediaController;  
  9. import android.widget.VideoView;  
  10.   
  11. public class MainActivity extends Activity {  
  12.   
  13.     @Override  
  14.     protected void onCreate(Bundle savedInstanceState) {  
  15.         super.onCreate(savedInstanceState);  
  16.         setContentView(R.layout.activity_main);  
  17.           
  18.         MediaPlayer mp=new MediaPlayer();  
  19.         try{  
  20.             mp.setDataSource("/sdcard/Music/maine.mp3");//Write your location here  
  21.             mp.prepare();  
  22.             mp.start();  
  23.               
  24.         }catch(Exception e){e.printStackTrace();}  
  25.           
  26.     }  
  27.   
  28.     @Override  
  29.     public boolean onCreateOptionsMenu(Menu menu) {  
  30.         // Inflate the menu; this adds items to the action bar if it is present.  
  31.         getMenuInflater().inflate(R.menu.activity_main, menu);  
  32.         return true;  
  33.     }  
  34.   
  35. }  

You need to run it on the real device to test the application.


Android MediaPlayer Example of controlling the audio

Let's see a simple example to start, stop and pause the audio play.

activity_main.xml

Drag three buttons from pallete to start, stop and pause the audio play. Now the xml file will look like this:
File: MainActivity.java
  1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:paddingBottom="@dimen/activity_vertical_margin"  
  6.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  7.     android:paddingRight="@dimen/activity_horizontal_margin"  
  8.     android:paddingTop="@dimen/activity_vertical_margin"  
  9.     tools:context=".MainActivity" >  
  10.   
  11.     <TextView  
  12.         android:id="@+id/textView1"  
  13.         android:layout_width="wrap_content"  
  14.         android:layout_height="wrap_content"  
  15.         android:layout_alignParentTop="true"  
  16.         android:layout_marginTop="30dp"  
  17.         android:text="Audio Controller" />  
  18.   
  19.     <Button  
  20.         android:id="@+id/button1"  
  21.         style="?android:attr/buttonStyleSmall"  
  22.         android:layout_width="wrap_content"  
  23.         android:layout_height="wrap_content"  
  24.         android:layout_alignLeft="@+id/textView1"  
  25.         android:layout_below="@+id/textView1"  
  26.         android:layout_marginTop="48dp"  
  27.         android:text="start" />  
  28.   
  29.     <Button  
  30.         android:id="@+id/button2"  
  31.         style="?android:attr/buttonStyleSmall"  
  32.         android:layout_width="wrap_content"  
  33.         android:layout_height="wrap_content"  
  34.         android:layout_alignTop="@+id/button1"  
  35.         android:layout_toRightOf="@+id/button1"  
  36.         android:text="pause" />  
  37.   
  38.     <Button  
  39.         android:id="@+id/button3"  
  40.         style="?android:attr/buttonStyleSmall"  
  41.         android:layout_width="wrap_content"  
  42.         android:layout_height="wrap_content"  
  43.         android:layout_alignTop="@+id/button2"  
  44.         android:layout_toRightOf="@+id/button2"  
  45.         android:text="stop" />  
  46.   
  47. </RelativeLayout>  

Activity class

Let's write the code to start, pause and stop the audio player.
File: MainActivity.java
  1. package com.example.audioplay;  
  2.   
  3. import android.media.MediaPlayer;  
  4. import android.os.Bundle;  
  5. import android.os.Environment;  
  6. import android.app.Activity;  
  7. import android.view.Menu;  
  8. import android.view.View;  
  9. import android.view.View.OnClickListener;  
  10. import android.widget.Button;  
  11.   
  12. public class MainActivity extends Activity {  
  13.     Button start,pause,stop;  
  14.     @Override  
  15.     protected void onCreate(Bundle savedInstanceState) {  
  16.         super.onCreate(savedInstanceState);  
  17.         setContentView(R.layout.activity_main);  
  18.           
  19.         start=(Button)findViewById(R.id.button1);  
  20.         pause=(Button)findViewById(R.id.button2);  
  21.         stop=(Button)findViewById(R.id.button3);  
  22.         //creating media player  
  23.         final MediaPlayer mp=new MediaPlayer();  
  24.         try{  
  25.                 //you can change the path, here path is external directory(e.g. sdcard) /Music/maine.mp3  
  26.         mp.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/Music/maine.mp3");  
  27.           
  28.         mp.prepare();  
  29.         }catch(Exception e){e.printStackTrace();}  
  30.           
  31.         start.setOnClickListener(new OnClickListener() {  
  32.             @Override  
  33.             public void onClick(View v) {  
  34.                 mp.start();  
  35.             }  
  36.         });  
  37.         pause.setOnClickListener(new OnClickListener() {  
  38.             @Override  
  39.             public void onClick(View v) {  
  40.                 mp.pause();  
  41.             }  
  42.         });  
  43.         stop.setOnClickListener(new OnClickListener() {  
  44.             @Override  
  45.             public void onClick(View v) {  
  46.                 mp.stop();  
  47.             }  
  48.         });  
  49.     }  
  50. }  


Output:

android audio control example output 1

Comments

Popular posts from this blog

Android Tutorial

Android  is a complete set of software for mobile devices such as tablet computers, notebooks, smartphones, electronic book readers, set-top boxes etc. It contains a  linux-based Operating System ,  middleware  and  key mobile applications . It can be thought of as a mobile operating system. But it is not limited to mobile only. It is currently used in various devices such as mobiles, tablets, televisions etc. This tutorial is developed for beginners and experienced persons. Let's see the topics of android that we are going to learn. Basics of Android In this fundamental chapter, you will learn about android, its components, how to create first android application, internal of first android application etc. What is Android History and Version Software Stack Core Building Blocks Android Emulator Installing softwares Setup Eclipse Hello Android example Internal Details Dalvik VM AndroidManifest.xml R.java Hide Title Bar Activity and I...

ABSTRACT

MULTI USER GSM BASED DIGITAL SCROLLING LED DISPLAY WITH PASSWORD AND VOICE ABSTRACT The project mainly focuses on transmission of textual data through air interface by the use of GSM through asynchronous serial communication. The data will be processed by the microcontroller it programmed by embedded c language by using KEIL C compiler. The data will be displayed on led display on LED only after entering unique pass key. Existing System: How a reliable and an authentic wireless communication could be easily developed between a mobile phone and microcontroller using GSM (Global System for Mobile Communication) MODEM (Modulator-Demodulator). This technical paper explains GSM based e-notice board which can be widely used for multitude of applications including educational sector, traffic control, banks, and public advertisements, stoke exchanges etc. Proposed System: In this project we not only send the data, but send the data with pass code also. Which enables us to preve...

A SHOULDER SURFING RESISTANT GRAPHICAL AUTHENTICATION SYSTEM

A SHOULDER SURFING RESISTANT GRAPHICAL AUTHENTICATION SYSTEM ABSTRACT Authentication based on passwords is used largely in applications for computer security and privacy. However, human actions such as choosing bad passwords and inputting passwords in an insecure way are regarded as”the weakest link” in the authentication chain. Rather than arbitrary alphanumeric strings, users tend to choose passwords either short or meaningful for easy memorization. With web applications and mobile apps piling up, people can access these applications anytime and anywhere with various devices. This evolution brings great convenience but also increases the probability of exposing passwords to shoulder surfing attacks. Attackers can observe directly or use external recording devices to collect users’ credentials. To overcome this problem, we proposed a novel authentication system PassMatrix, based on graphical passwords to resist shoulder surfing attacks. With a one-time valid login indicator and ...