Audio and Video Player Development
Audio and Video Player Development
Statement Purpose:
Here, we are going to see a simple example to play the audio/video file. In the next page, we will see the example to control the audio playback like start, stop, pause etc.
Activity Outcomes:
Students can play and control the audio/video files in android by the help of MediaPlayer class.
Instructor Note:
Media Player API
Android Multimedia Framework – android.media API
The android multimedia framework provides developers a way to easily integrate audio and video playback into applications, and supports most of the common media types. The MediaPlayer class is the key in android multimedia framework. It can be used to play media on the local file system, media files stored in the application‘s resources, as well as data streaming over a network connection.
Introduction
playing Audio
Probably the most basic need for multimedia on a cell phone is the ability to play audio files, whether new ringtones, MP3s, or quick audio notes. Media- Player of android is easy to use. To play an MP3 file follow these steps:
- Place the MP3 in the res/raw directory in a project (note that we can also use a URI to access files on the network or via the internet).
- Create a new instance of the MediaPlayer, and reference the MP3 by calling create().
- Call the MediaPlayer methods prepare() and start().
Playing Video
Playing a video is slightly more complicated than playing audio with the MediaPlayer API, because we have to provide a view surface for our video to play on. Android has a Video View widget that handles this task for us. This widget can be used with any layout manager. Android also provides a number of display options, including scaling and tinting.
Lab Activities:
Activity 1:
Activity_main.xml
<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayoutxmlns:android= xmlns:tools=android:layout_width=”match_parent” android:layout_height=”match_parent” android:paddingLeft=”@dimen/activity_horizontal_margin” android:paddingRight=”@dimen/activity_horizontal_margin” android:paddingTop=”@dimen/activity_vertical_margin” android:paddingBottom=”@dimen/activity_vertical_margin” tools:context=”com.example.ait.mediaplayer.MainActivity”>
<TextViewandroid:text=”Music Palyer” android:layout_width=”wrap_content” android:layout_height=”wrap_content”
android:id=”@+id/textview” android:textSize=”35sp” android:layout_alignParentTop=”true” android:layout_centerHorizontal=”true” tools:ignore=”HardcodedText” />
<TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials point” android:id=”@+id/textView” android:layout_below=”@+id/textview” android:layout_centerHorizontal=”true” android:textColor=”#ff7aff24″ android:textSize=”35sp” tools:ignore=”HardcodedText” />
<Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”@string/forward” android:id=”@+id/button” android:layout_alignParentBottom=”true” android:layout_alignParentLeft=”true” android:layout_alignParentStart=”true” />
<Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”@string/pause” android:id=”@+id/button2″ android:layout_alignParentBottom=”true” android:layout_alignLeft=”@+id/imageView”
android:layout_alignStart=”@+id/imageView” />
<Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”@string/back” android:id=”@+id/button3″ android:layout_alignTop=”@+id/button2″ android:layout_toRightOf=”@+id/button2″ android:layout_toEndOf=”@+id/button2″ />
<Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”@string/rewind” android:id=”@+id/button4″ android:layout_alignTop=”@+id/button3″ android:layout_toRightOf=”@+id/button3″ android:layout_toEndOf=”@+id/button3″ />
<SeekBar android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/seekBar” android:layout_alignLeft=”@+id/textview” android:layout_alignStart=”@+id/textview” android:layout_alignRight=”@+id/textview” android:layout_alignEnd=”@+id/textview” android:layout_above=”@+id/button” />
<ImageView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/imageView” android:src=”@drawable/abc” android:layout_below=”@+id/textview” android:layout_marginTop=”16dp” android:layout_alignLeft=”@+id/textView” android:layout_alignStart=”@+id/textView” android:layout_alignRight=”@+id/textView” android:layout_alignEnd=”@+id/textView” android:contentDescription=”” tools:ignore=”ContentDescription” />
<TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content”
android:textAppearance=”?android:attr/textAppearanceMedium” android:text=”Medium Text”
android:id=”@+id/textView4″ android:layout_above=”@+id/seekBar” android:layout_toLeftOf=”@+id/button4″ android:layout_toStartOf=”@+id/button4″ />
<TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content”
android:textAppearance=”?android:attr/textAppearanceSmall” android:text=”Small Text”
android:id=”@+id/textView3″ android:layout_above=”@+id/seekBar” android:layout_alignRight=”@+id/button4″ android:layout_alignEnd=”@+id/button4″ />
<TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content”
android:textAppearance=”?android:attr/textAppearanceSmall” android:text=”Small Text”
android:id=”@+id/textView2″ android:layout_alignTop=”@+id/textView4″ android:layout_toLeftOf=”@+id/seekBar” android:layout_toStartOf=”@+id/seekBar” />
</RelativeLayout>
Manifest
<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=“http://schemas.android.com/apk/res/android“ package=”com.example.ait.mediaplayer” >
<application android:allowBackup=”true” android:icon=”@drawable/abc” android:label=”@string/app_name” android:theme=”@style/AppTheme” >
<activity android:name=”com.example.ait.mediaplayer.MainActivity” android:label=”@string/app_name” >
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
</application>
</manifest>
Strings
<resources>
<string name=”app_name”>Mediaplayer</string>
<string name=”back”><![CDATA[<]]></string>
<string name=”rewind”><![CDATA[<<]]></string>
<string name=”forward”><![CDATA[>>]]></string>
<string name=”pause”>||</string>
</resources>
MainActivity.java
package com.example.ait.mediaplayer;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.Button;
import android.widget.ImageView; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast;
import java.util.concurrent.TimeUnit; public class MainActivityextends Activity { private Button b1,b2,b3,b4;
private ImageViewiv;
private MediaPlayermediaPlayer; private double startTime= 0; private double finalTime= 0;
private Handler myHandler= new Handler();;
private intforwardTime= 5000;
private intbackwardTime= 5000;
private SeekBarseekbar;
private TextViewtx1,tx2,tx3; public static intoneTimeOnly= 0; @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button); b2 = (Button) findViewById(R.id.button2); b3 = (Button)findViewById(R.id.button3); b4 = (Button)findViewById(R.id.button4);
iv = (ImageView)findViewById(R.id.imageView); tx1 = (TextView)findViewById(R.id.textView2); tx2 = (TextView)findViewById(R.id.textView3); tx3 = (TextView)findViewById(R.id.textView4); tx3.setText(“Song.mp3”);
mediaPlayer= MediaPlayer.create(this, R.raw.sss); seekbar= (SeekBar)findViewById(R.id.seekBar); seekbar.setClickable(false);
b2.setEnabled(false);
b3.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
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;
}
tx2.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)))
);
tx1.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); b2.setEnabled(true);
b3.setEnabled(false);
}
});
b2.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), “Pausing sound”,Toast.LENGTH_SHORT).show(); mediaPlayer.pause();
b2.setEnabled(false); b3.setEnabled(true);
}
});
b1.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
inttemp = (int)startTime;
if((temp+forwardTime)<=finalTime){ startTime= startTime+ forwardTime; mediaPlayer.seekTo((int) startTime);
Toast.makeText(getApplicationContext(),“You have Jumped forward 5 seconds”,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),“Cannot jump forward 5 seconds”,Toast.LENGTH_SHORT).show();
}
}
});
if((temp-backwardTime)>0){ startTime= startTime– backwardTime; mediaPlayer.seekTo((int) startTime);
Toast.makeText(getApplicationContext(),“You have Jumped backward 5 seconds”,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),“Cannot jump backward 5 seconds”,Toast.LENGTH_SHORT).show();
}
}
});
}
private Runnable UpdateSongTime= new Runnable() {
public void run() {
startTime= mediaPlayer.getCurrentPosition();
tx1.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);
}
};
}
OUTPUT:
Playing Video
Manifest
<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.ait.videoplayer”>
<uses-permission android:name=”android.permission.INTERNET”></uses-permission>
<application android:allowBackup=”true” android:icon=”@mipmap/ic_launcher” android:label=”@string/app_name” android:supportsRtl=”true” android:theme=”@style/AppTheme”>
<activity android:name=”.MainActivity”>
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
</application>
</manifest>
Strings
<resources>
<string name=”app_name”>My Application</string>
<string name=”hello_world”>Hello world!</string>
<string name=”action_settings”>Settings</string>
</resources>
Activity_main.xml
<?xml version=”1.0″ encoding=”utf-8″?>
<FrameLayoutxmlns: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=”com.example.ait.videoplayer.MainActivity”>
<VideoView android:layout_width=”fill_parent” android:layout_height=”fill_parent” android:id=”@+id/videoView” android:layout_gravity=”center” />
</FrameLayout>
MainActivity.java
package com.example.ait.videoplayer;
import android.support.v7.app.AppCompatActivity; import android.os.Bundle;
import android.support.v7.app.AppCompatActivity; import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog; import android.content.res.Configuration; import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener; import android.net.Uri;
import android.os.Bundle; import android.util.Log;
import android.widget.MediaController; import android.widget.VideoView;
public class MainActivityextends AppCompatActivity { private VideoViewvideoView;
private intposition = 0;
private MediaControllermediaController;
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
videoView= (VideoView) findViewById(R.id.videoView);
// Set the media controller buttons
if (mediaController== null) {
mediaController= new MediaController(MainActivity.this);
// Set the videoView that acts as the anchor for the MediaController.
mediaController.setAnchorView(videoView);
// Set MediaController for VideoView
videoView.setMediaController(mediaController);
}
try {
// ID of video file.
intid = this.getRawResIdByName(“wildlife”); videoView.setVideoURI(Uri.parse(“android.resource://” + getPackageName() + “/” + id));
} catch (Exception e) { Log.e(“Error”, e.getMessage()); e.printStackTrace();
}
videoView.requestFocus(); videoView.setOnPreparedListener(new OnPreparedListener() { public void onPrepared(MediaPlayermediaPlayer) { videoView.seekTo(position);
if (position == 0) { videoView.start();
}
mediaPlayer.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() { @Override
public void onVideoSizeChanged(MediaPlayermp, intwidth, intheight) { mediaController.setAnchorView(videoView);
}
});
}
});
}
// Find ID corresponding to the name of the resource (in the directory raw).
publicintgetRawResIdByName(String resName) { String pkgName = this.getPackageName();
// Return 0 if not found.
intresID = this.getResources().getIdentifier(resName, “raw”, pkgName); Log.i(“AndroidVideoView”, “Res Name: ” + resName + “==> Res ID = ” + resID); return resID;
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState);
// Store current position.
savedInstanceState.putInt(“CurrentPosition”, videoView.getCurrentPosition()); videoView.pause();
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState);
// Get saved position.
position = savedInstanceState.getInt(“CurrentPosition”); videoView.seekTo(position);
}
OUTPUT
Home Activities:
Activity 1:
Make an application that takes the video from the sdcard and play it and save it with another name in the same file and assets folder.