SlideShare a Scribd company logo
Chapter 23
Media
By
Dr. Ramkumar Lakshminarayanan
Introduction
Android’s robust APIs can be used to add video, audio, and photo capabilities to app for
playing and recording media. 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.
Media Playback
MediaPlayer APIs are used to play audio or video from media files stored in the
application's resources (raw resources), from standalone files in the filesystem, or from a data
stream arriving over a network connection.
You can play back the audio data only to the standard output device. Currently, that is the
mobile device speaker or a Bluetooth headset. You cannot play sound files in the conversation
audio during a call.
The following classes are used to play sound and video in the Android framework:
 MediaPlayer- This class is the primary API for playing sound and
 video.AudioManager - This class manages audio sources and audio output on a
device.
Manifest Declaration
Before starting development on your application using MediaPlayer, make sure your manifest
has the appropriate declarations to allow use of related features.
 Internet Permission - If you are using MediaPlayer to stream network-based content, your
application must request network access.
 Wake Lock Permission - If your player application needs to keep the screen from
dimming or the processor from sleeping, or uses the
<uses-permissionandroid:name="android.permission.INTERNET" />
MediaPlayer.setScreenOnWhilePlaying() or MediaPlayer.setWakeMode() methods, you
must request this permission.
Media Player
One of the most important components of the media framework is the
MediaPlayer class. An object of this class can fetch, decode, and play both audio and
video with minimal setup. It supports several different media sources such as:
• Local resources
• Internal URIs, such as one you might obtain from a Content Resolver
• External URLs (streaming)
Here is an example of how to play audio that's available as a local raw resource
(saved in your application's res/raw/ directory):
In this case, a "raw" resource is a file that the system does not try to parse in any
particular way. However, the content of this resource should not be raw audio. It should
be a properly encoded and formatted media file in one of the supported formats.
And here is how you might play from a URI available locally in the system (that
you obtained through a Content Resolver, for instance):
Playing from a remote URL via HTTP streaming looks like this:
Audio Capture
<uses-permissionandroid:name="android.permission.WAKE_LOCK"/>
Uri myUri = ....;// initialize Uri here
MediaPlayermediaPlayer=new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(getApplicationContext(),myUri);
mediaPlayer.prepare();
mediaPlayer.start();
Stringurl = "http://........";//yourURL here
MediaPlayermediaPlayer=new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();//mighttake long!(forbuffering,etc)
mediaPlayer.start();
The Android multimedia framework includes support for capturing and encoding a
variety of common audio formats, so that you can easily integrate audio into your applications.
You can record audio using the MediaRecorder APIs if supported by the device hardware.
Audio capture from the device is a bit more complicated than audio and video playback,
but still fairly simple:
1.Create a new instance of android.media.MediaRecorder.
2.Set the audio source using MediaRecorder.setAudioSource(). You will probably want
to use MediaRecorder.AudioSource.MIC.
3.Set output file format using MediaRecorder.setOutputFormat().
4.Set output file name using MediaRecorder.setOutputFile().
5.Set the audio encoder using MediaRecorder.setAudioEncoder().
6.Call MediaRecorder.prepare() on the MediaRecorder instance.
7.To start audio capture, call MediaRecorder.start().
8.To stop audio capture, call MediaRecorder.stop().
9.When you are done with the MediaRecorder instance, call MediaRecorder.release() on
it. Calling MediaRecorder.release() is always recommended to free the resource immediately.
Example: Record audio and play the recorded audio
The example class below illustrates how to set up, start and stop audio capture, and to
play the recorded audio file.
/* The application needs to have the permission to write to external storage
* if the output file is written to the external storage, and also the
* permission to r/*
* The application needs to have the permission to write to external storage
* if the output file is written to the external storage, and also the
* permission to record audio. These permissions must be set in the
* application's AndroidManifest.xml file, with something like:
* <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
* <uses-permission android:name="android.permission.RECORD_AUDIO" />
*/
package com.android.audiorecordtest;
import android.app.Activity;
import android.widget.LinearLayout;
import android.os.Bundle;
import android.os.Environment;
import android.view.ViewGroup;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.content.Context;
publicclassAudioRecordTestextendsActivity
{
private staticfinal StringLOG_TAG = "AudioRecordTest";
private staticStringmFileName =null;
private RecordButtonmRecordButton=null;
private MediaRecordermRecorder=null;
private PlayButton mPlayButton=null;
private MediaPlayer mPlayer=null;
private voidonRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private voidonPlay(booleanstart) {
if (start) {
startPlaying();
} else {
stopPlaying();
}
}
private voidstartPlaying() {
mPlayer=newMediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOExceptione) {
Log.e(LOG_TAG,"prepare() failed");
}
}
private voidstopPlaying(){
mPlayer.release();
mPlayer=null;
}
private voidstartRecording(){
mRecorder= newMediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
class RecordButton extends Button {
boolean mStartRecording = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
setText("Stop recording");
} else {
setText("Start recording");
}
mStartRecording = !mStartRecording;
}
};
public RecordButton(Context ctx) {
super(ctx);
setText("Start recording");
setOnClickListener(clicker);
}
}
class PlayButton extends Button {
boolean mStartPlaying = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onPlay(mStartPlaying);
if (mStartPlaying) {
setText("Stop playing");
} else {
setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
};
public PlayButton(Context ctx) {
super(ctx);
setText("Start playing");
setOnClickListener(clicker);
}
}
publicAudioRecordTest() {
mFileName =Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName +="/audiorecordtest.3gp";
}
@Override
publicvoidonCreate(Bundle icicle){
super.onCreate(icicle);
LinearLayoutll =newLinearLayout(this);
mRecordButton=newRecordButton(this);
ll.addView(mRecordButton,
newLinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
mPlayButton=newPlayButton(this);
ll.addView(mPlayButton,
newLinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
setContentView(ll);
}
@Override
publicvoidonPause(){
super.onPause();
if (mRecorder!=null) {
mRecorder.release();
mRecorder= null;
}
if (mPlayer!=null) {
mPlayer.release();
mPlayer= null;
}
}
}
Summary
In this unit we have discussed about the Media API in Android and set up, start and stop
audio capture, and to play the recorded audio file.

More Related Content

PDF
2016-08-20 01 Дмитрий Рабецкий, Сергей Сорокин. Опыт работы с Android Medi...
PPT
Mk seminar
PPTX
5 pen technology
PPTX
Android Training (Media)
PDF
Best Practices in Media Playback
PDF
Android media
PDF
Best Practices in Media Playback
PPT
Android application structure
2016-08-20 01 Дмитрий Рабецкий, Сергей Сорокин. Опыт работы с Android Medi...
Mk seminar
5 pen technology
Android Training (Media)
Best Practices in Media Playback
Android media
Best Practices in Media Playback
Android application structure

Similar to Android media-chapter 23 (20)

PPTX
UNIT5newpart1pptx__2024_11_13_09_51_59 (1).pptx
PPTX
Android development-tutorial
PPTX
Android security by ravi-rai
PPTX
Android Studio development model and.pptx
PDF
Android media framework overview
PDF
Scoped storage in android 10 all you need to know
PPTX
Android application
PPT
Android For Java Developers
PPT
Level 3
PPTX
03 android application structure
PPTX
Mobile application Development-UNIT-V (1).pptx
PPTX
2.Android Platform_Theory.pptx
PPT
Chapter03 Of It .... BBa 1st
PPTX
Android Overview
PPTX
How to create android applications
PPSX
Designing of Video Player with Python
PDF
Get On The Audiobus (CocoaConf Atlanta, November 2013)
PPT
Introduction to android
PPT
Software and its types
UNIT5newpart1pptx__2024_11_13_09_51_59 (1).pptx
Android development-tutorial
Android security by ravi-rai
Android Studio development model and.pptx
Android media framework overview
Scoped storage in android 10 all you need to know
Android application
Android For Java Developers
Level 3
03 android application structure
Mobile application Development-UNIT-V (1).pptx
2.Android Platform_Theory.pptx
Chapter03 Of It .... BBa 1st
Android Overview
How to create android applications
Designing of Video Player with Python
Get On The Audiobus (CocoaConf Atlanta, November 2013)
Introduction to android
Software and its types
Ad

More from Dr. Ramkumar Lakshminarayanan (20)

PPT
IT security awareness
PPT
Basics of IT security
PDF
IT Security Awareness Posters
PPT
Normalisation revision
PPTX
Windows mobile programming
PPTX
Concurrency control
PPT
Web technology today
PDF
Phonegap for Android
PDF
Create and Sell Android App (in tamil)
PDF
Android app - Creating Live Wallpaper (tamil)
PDF
Android Tips (Tamil)
PDF
Android Animation (in tamil)
PDF
Creating List in Android App (in tamil)
PDF
Single Touch event view in Android (in tamil)
PDF
Android Application using seekbar (in tamil)
PDF
Rating Bar in Android Example
PDF
Creating Image Gallery - Android app (in tamil)
PDF
Create Android App using web view (in tamil)
PDF
Hardware Interface in Android (in tamil)
IT security awareness
Basics of IT security
IT Security Awareness Posters
Normalisation revision
Windows mobile programming
Concurrency control
Web technology today
Phonegap for Android
Create and Sell Android App (in tamil)
Android app - Creating Live Wallpaper (tamil)
Android Tips (Tamil)
Android Animation (in tamil)
Creating List in Android App (in tamil)
Single Touch event view in Android (in tamil)
Android Application using seekbar (in tamil)
Rating Bar in Android Example
Creating Image Gallery - Android app (in tamil)
Create Android App using web view (in tamil)
Hardware Interface in Android (in tamil)
Ad

Recently uploaded (6)

PPTX
ASMS Telecommunication company Profile
PPTX
Introduction to Packet Tracer Course Overview - Aug 21 (1).pptx
DOC
证书学历UoA毕业证,澳大利亚中汇学院毕业证国外大学毕业证
PDF
Lesson 13- HEREDITY _ pedSAWEREGFVCXZDSASEWFigree.pdf
PDF
6-UseCfgfhgfhgfhgfhgfhfhhaseActivity.pdf
DOC
Camb毕业证学历认证,格罗斯泰斯特主教大学毕业证仿冒文凭毕业证
ASMS Telecommunication company Profile
Introduction to Packet Tracer Course Overview - Aug 21 (1).pptx
证书学历UoA毕业证,澳大利亚中汇学院毕业证国外大学毕业证
Lesson 13- HEREDITY _ pedSAWEREGFVCXZDSASEWFigree.pdf
6-UseCfgfhgfhgfhgfhgfhfhhaseActivity.pdf
Camb毕业证学历认证,格罗斯泰斯特主教大学毕业证仿冒文凭毕业证

Android media-chapter 23

  • 1. Chapter 23 Media By Dr. Ramkumar Lakshminarayanan Introduction Android’s robust APIs can be used to add video, audio, and photo capabilities to app for playing and recording media. 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. Media Playback MediaPlayer APIs are used to play audio or video from media files stored in the application's resources (raw resources), from standalone files in the filesystem, or from a data stream arriving over a network connection. You can play back the audio data only to the standard output device. Currently, that is the mobile device speaker or a Bluetooth headset. You cannot play sound files in the conversation audio during a call. The following classes are used to play sound and video in the Android framework:  MediaPlayer- This class is the primary API for playing sound and  video.AudioManager - This class manages audio sources and audio output on a device. Manifest Declaration Before starting development on your application using MediaPlayer, make sure your manifest has the appropriate declarations to allow use of related features.  Internet Permission - If you are using MediaPlayer to stream network-based content, your application must request network access.  Wake Lock Permission - If your player application needs to keep the screen from dimming or the processor from sleeping, or uses the <uses-permissionandroid:name="android.permission.INTERNET" />
  • 2. MediaPlayer.setScreenOnWhilePlaying() or MediaPlayer.setWakeMode() methods, you must request this permission. Media Player One of the most important components of the media framework is the MediaPlayer class. An object of this class can fetch, decode, and play both audio and video with minimal setup. It supports several different media sources such as: • Local resources • Internal URIs, such as one you might obtain from a Content Resolver • External URLs (streaming) Here is an example of how to play audio that's available as a local raw resource (saved in your application's res/raw/ directory): In this case, a "raw" resource is a file that the system does not try to parse in any particular way. However, the content of this resource should not be raw audio. It should be a properly encoded and formatted media file in one of the supported formats. And here is how you might play from a URI available locally in the system (that you obtained through a Content Resolver, for instance): Playing from a remote URL via HTTP streaming looks like this: Audio Capture <uses-permissionandroid:name="android.permission.WAKE_LOCK"/> Uri myUri = ....;// initialize Uri here MediaPlayermediaPlayer=new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setDataSource(getApplicationContext(),myUri); mediaPlayer.prepare(); mediaPlayer.start(); Stringurl = "http://........";//yourURL here MediaPlayermediaPlayer=new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setDataSource(url); mediaPlayer.prepare();//mighttake long!(forbuffering,etc) mediaPlayer.start();
  • 3. The Android multimedia framework includes support for capturing and encoding a variety of common audio formats, so that you can easily integrate audio into your applications. You can record audio using the MediaRecorder APIs if supported by the device hardware. Audio capture from the device is a bit more complicated than audio and video playback, but still fairly simple: 1.Create a new instance of android.media.MediaRecorder. 2.Set the audio source using MediaRecorder.setAudioSource(). You will probably want to use MediaRecorder.AudioSource.MIC. 3.Set output file format using MediaRecorder.setOutputFormat(). 4.Set output file name using MediaRecorder.setOutputFile(). 5.Set the audio encoder using MediaRecorder.setAudioEncoder(). 6.Call MediaRecorder.prepare() on the MediaRecorder instance. 7.To start audio capture, call MediaRecorder.start(). 8.To stop audio capture, call MediaRecorder.stop(). 9.When you are done with the MediaRecorder instance, call MediaRecorder.release() on it. Calling MediaRecorder.release() is always recommended to free the resource immediately. Example: Record audio and play the recorded audio The example class below illustrates how to set up, start and stop audio capture, and to play the recorded audio file. /* The application needs to have the permission to write to external storage * if the output file is written to the external storage, and also the * permission to r/* * The application needs to have the permission to write to external storage * if the output file is written to the external storage, and also the * permission to record audio. These permissions must be set in the * application's AndroidManifest.xml file, with something like: * <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> * <uses-permission android:name="android.permission.RECORD_AUDIO" /> */ package com.android.audiorecordtest; import android.app.Activity; import android.widget.LinearLayout; import android.os.Bundle; import android.os.Environment; import android.view.ViewGroup; import android.widget.Button; import android.view.View; import android.view.View.OnClickListener; import android.content.Context;
  • 4. publicclassAudioRecordTestextendsActivity { private staticfinal StringLOG_TAG = "AudioRecordTest"; private staticStringmFileName =null; private RecordButtonmRecordButton=null; private MediaRecordermRecorder=null; private PlayButton mPlayButton=null; private MediaPlayer mPlayer=null; private voidonRecord(boolean start) { if (start) { startRecording(); } else { stopRecording(); } } private voidonPlay(booleanstart) { if (start) { startPlaying(); } else { stopPlaying(); } } private voidstartPlaying() { mPlayer=newMediaPlayer(); try { mPlayer.setDataSource(mFileName); mPlayer.prepare(); mPlayer.start(); } catch (IOExceptione) { Log.e(LOG_TAG,"prepare() failed"); } } private voidstopPlaying(){ mPlayer.release(); mPlayer=null; } private voidstartRecording(){ mRecorder= newMediaRecorder(); mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); mRecorder.setOutputFile(mFileName); mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); try { mRecorder.prepare();
  • 5. private void stopRecording() { mRecorder.stop(); mRecorder.release(); mRecorder = null; } class RecordButton extends Button { boolean mStartRecording = true; OnClickListener clicker = new OnClickListener() { public void onClick(View v) { onRecord(mStartRecording); if (mStartRecording) { setText("Stop recording"); } else { setText("Start recording"); } mStartRecording = !mStartRecording; } }; public RecordButton(Context ctx) { super(ctx); setText("Start recording"); setOnClickListener(clicker); } } class PlayButton extends Button { boolean mStartPlaying = true; OnClickListener clicker = new OnClickListener() { public void onClick(View v) { onPlay(mStartPlaying); if (mStartPlaying) { setText("Stop playing"); } else { setText("Start playing"); } mStartPlaying = !mStartPlaying; } }; public PlayButton(Context ctx) { super(ctx); setText("Start playing"); setOnClickListener(clicker); } }
  • 6. publicAudioRecordTest() { mFileName =Environment.getExternalStorageDirectory().getAbsolutePath(); mFileName +="/audiorecordtest.3gp"; } @Override publicvoidonCreate(Bundle icicle){ super.onCreate(icicle); LinearLayoutll =newLinearLayout(this); mRecordButton=newRecordButton(this); ll.addView(mRecordButton, newLinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0)); mPlayButton=newPlayButton(this); ll.addView(mPlayButton, newLinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0)); setContentView(ll); } @Override publicvoidonPause(){ super.onPause(); if (mRecorder!=null) { mRecorder.release(); mRecorder= null; } if (mPlayer!=null) { mPlayer.release(); mPlayer= null; } } }
  • 7. Summary In this unit we have discussed about the Media API in Android and set up, start and stop audio capture, and to play the recorded audio file.