articles

Home / DeveloperSection / Articles / Handling Media with Android

Handling Media with Android

Manoj Pandey4376 13-Mar-2015

Android provides two main API's for playing sounds. The first one via the SoundPool class and the other one via the MediaPlayer class.

SoundPool can be used for small audio clips. It can repeat sounds and play several sounds simultaneously. The sound files played with SoundPool should not exceed 1 MB.

Android supports different audio streams for different purposes. The phone volume button can be configured to control a specific audio stream, e.g. during a call the volume button allow increase / decrease the caller volume.

MediaPlayer is better suited for longer music and movies.

The Android multimedia framework includes support for playing variety of common media types, so that you can easily integrate audio, video and images into your applications. You can play audio or video from media files stored in your application's resources (raw resources), from standalone files in the filesystem, or from a data stream arriving over a network connection, all using MediaPlayer APIs.

Here I am creating a sample of mediaplayer with audio example

1.      Create an android project

2.      Add views in activity_main.xml fie

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context=".MainActivity" >

 

    <ImageButton

        android:id="@+id/imageButton3"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignParentBottom="true"

        android:layout_alignParentLeft="true"

        android:layout_marginBottom="14dp"

        android:onClick="forward"

        android:src="@android:drawable/ic_media_ff" />

 

    <ImageButton

        android:id="@+id/imageButton4"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignParentRight="true"

        android:layout_alignTop="@+id/imageButton2"

        android:layout_marginLeft="22dp"

        android:layout_toRightOf="@+id/imageButton2"

        android:onClick="rewind"

        android:src="@android:drawable/ic_media_rew" />

 

    <ImageButton

        android:id="@+id/imageButton2"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignTop="@+id/imageButton1"

        android:layout_marginLeft="14dp"

        android:layout_toRightOf="@+id/imageButton1"

        android:onClick="pause"

        android:src="@android:drawable/ic_media_pause" />

 

    <ImageButton

        android:id="@+id/imageButton1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignTop="@+id/imageButton3"

        android:layout_marginLeft="24dp"

        android:layout_toRightOf="@+id/imageButton3"

        android:onClick="play"

        android:src="@android:drawable/ic_media_play" />

 

    <SeekBar

        android:id="@+id/seekBar1"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_above="@+id/imageButton3"

        android:layout_toLeftOf="@+id/textView2"

        android:layout_toRightOf="@+id/textView1" />

 

    <TextView

        android:id="@+id/textView1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignRight="@+id/imageButton3"

        android:layout_alignTop="@+id/seekBar1"

        android:text="@string/inital_Time"

        android:textAppearance="?android:attr/textAppearanceSmall" />

 

    <TextView

        android:id="@+id/textView2"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignLeft="@+id/imageButton4"

        android:layout_alignTop="@+id/seekBar1"

        android:text="@string/inital_Time"

        android:textAppearance="?android:attr/textAppearanceSmall" />

 

    <TextView

        android:id="@+id/textView3"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignLeft="@+id/imageButton3"

        android:text="@string/hello_world"

        android:textAppearance="?android:attr/textAppearanceMedium" />

 

    <ImageView

        android:id="@+id/imageView1"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:layout_alignParentBottom="true"

        android:layout_alignParentLeft="true"

        android:layout_below="@+id/textView3"

        android:src="@drawable/ic_launcher" />

 

    <TextView

        android:id="@+id/textView4"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignBaseline="@+id/textView3"

        android:layout_alignBottom="@+id/textView3"

        android:layout_toRightOf="@+id/imageButton1"

        android:text="TextView" />

 

</RelativeLayout>

3.      Create new raw folder in res/drawable and mp3 song

4.      Add following code in MainActivity.class

package com.example.androidmedia; 

import java.util.concurrent.TimeUnit; 

import android.media.MediaPlayer;

import android.os.Bundle;

import android.os.Handler;

import android.app.Activity;

import android.view.Menu;

import android.view.View;

import android.widget.ImageButton;

import android.widget.SeekBar;

import android.widget.TextView;

import android.widget.Toast;

 

public class MainActivity extends Activity {

 

     public TextView songName, startTimeField, endTimeField;

     private MediaPlayer mediaPlayer;

     private double startTime = 0;

     private double finalTime = 0;

     private Handler myHandler = new Handler();;

     private int forwardTime = 5000;

     private int backwardTime = 5000;

     private SeekBar seekbar;

     private ImageButton playButton, pauseButton;

     public static int oneTimeOnly = 0;

 

     @Override

     protected void onCreate(Bundle savedInstanceState) {

           super.onCreate(savedInstanceState);

           setContentView(R.layout.activity_main);

           songName = (TextView) findViewById(R.id.textView4);

           startTimeField = (TextView) findViewById(R.id.textView1);

           endTimeField = (TextView) findViewById(R.id.textView2);

           seekbar = (SeekBar) findViewById(R.id.seekBar1);

           playButton = (ImageButton) findViewById(R.id.imageButton1);

           pauseButton = (ImageButton) findViewById(R.id.imageButton2);

           songName.setText("song.mp3");

           mediaPlayer = MediaPlayer.create(this, R.raw.sun);

           seekbar.setClickable(false);

           pauseButton.setEnabled(false);

 

     }

 

     // Play media player

     public void play(View view) {

           Toast.makeText(getApplicationContext(), "Playing sound",

                     Toast.LENGTH_SHORT).show();

           mediaPlayer.start();

           finalTime = mediaPlayer.getDuration();

           startTime = mediaPlayer.getCurrentPosition();

           if (oneTimeOnly == 0) {

                seekbar.setMax((int) finalTime);

                oneTimeOnly = 1;

           }

 

           endTimeField.setText(String.format(

                     "%d min, %d sec",

                    TimeUnit.MILLISECONDS.toMinutes((long) finalTime),

                     TimeUnit.MILLISECONDS.toSeconds((long) finalTime)

                    - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS

                                     .toMinutes((long) finalTime))));

           startTimeField.setText(String.format(

                     "%d min, %d sec",

                    TimeUnit.MILLISECONDS.toMinutes((long) startTime),

                     TimeUnit.MILLISECONDS.toSeconds((long) startTime)

                    - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS

                          .toMinutes((long) startTime))));

           seekbar.setProgress((int) startTime);

           myHandler.postDelayed(UpdateSongTime, 100);

           pauseButton.setEnabled(true);

           playButton.setEnabled(false);

     }

 

     private Runnable UpdateSongTime = new Runnable() {

           public void run() {

 

                startTime = mediaPlayer.getCurrentPosition();

                startTimeField.setText(String.format(

                           "%d min, %d sec",

                    TimeUnit.MILLISECONDS.toMinutes((long) startTime),

                     TimeUnit.MILLISECONDS.toSeconds((long) startTime)

                    - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS

                      .toMinutes((long) startTime))));

                seekbar.setProgress((int) startTime);

                myHandler.postDelayed(this, 100);

           }

     };

 

     public void pause(View view) {

           Toast.makeText(getApplicationContext(), "Pausing sound",

                     Toast.LENGTH_SHORT).show();

           // stop media player

           mediaPlayer.pause();

           pauseButton.setEnabled(false);

           playButton.setEnabled(true);

     }

 

     // Increase time 5 sec from current time

     public void forward(View view) {

           int temp = (int) startTime;

           if ((temp + forwardTime) <= finalTime) {

                startTime = startTime + forwardTime;

                mediaPlayer.seekTo((int) startTime);

           } else {

           Toast.makeText(getApplicationContext(),

           "Cannot jump forward 5 seconds", Toast.LENGTH_SHORT).show();

           }

 

     }

 

     // Decrease time 5 sec from current time

     public void rewind(View view) {

           int temp = (int) startTime;

           if ((temp - backwardTime) > 0) {

                startTime = startTime - backwardTime;

                mediaPlayer.seekTo((int) startTime);

           } else {

                Toast.makeText(getApplicationContext(),

                 "Cannot jump backward 5 seconds", Toast.LENGTH_SHORT)

                           .show();

           }

 

     }

 

     @Override

     public boolean onCreateOptionsMenu(Menu menu) {

          // Inflate the menu; this adds items to the action bar if it //is present.

           getMenuInflater().inflate(R.menu.main, menu);

           return true;

     }

 

}

Now run your application 

Handling Media with Android


Updated 07-Sep-2019

Leave Comment

Comments

Liked By