SlideShare ist ein Scribd-Unternehmen logo
1 von 7
Downloaden Sie, um offline zu lesen
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.

Weitere ähnliche Inhalte

Ähnlich wie Android media-chapter 23

Android development-tutorial
Android development-tutorialAndroid development-tutorial
Android development-tutorialilias ahmed
 
Android security by ravi-rai
Android security by ravi-raiAndroid security by ravi-rai
Android security by ravi-raiRavi Rai
 
Android media framework overview
Android media framework overviewAndroid media framework overview
Android media framework overviewJerrin George
 
Scoped storage in android 10 all you need to know
Scoped storage in android 10  all you need to knowScoped storage in android 10  all you need to know
Scoped storage in android 10 all you need to knowRobertJackson147
 
Android For Java Developers
Android For Java DevelopersAndroid For Java Developers
Android For Java DevelopersMike Wolfson
 
03 android application structure
03 android application structure03 android application structure
03 android application structureSokngim Sa
 
2.Android Platform_Theory.pptx
2.Android Platform_Theory.pptx2.Android Platform_Theory.pptx
2.Android Platform_Theory.pptxNizarnizarsurche
 
Chapter03 Of It .... BBa 1st
Chapter03 Of It .... BBa 1st Chapter03 Of It .... BBa 1st
Chapter03 Of It .... BBa 1st Geo-Info Ltd
 
Android Overview
Android OverviewAndroid Overview
Android OverviewRaju Kadam
 
How to create android applications
How to create android applicationsHow to create android applications
How to create android applicationsTOPS Technologies
 
Designing of Video Player with Python
Designing of Video Player with PythonDesigning of Video Player with Python
Designing of Video Player with PythonHASIM ALI
 
Get On The Audiobus (CocoaConf Atlanta, November 2013)
Get On The Audiobus (CocoaConf Atlanta, November 2013)Get On The Audiobus (CocoaConf Atlanta, November 2013)
Get On The Audiobus (CocoaConf Atlanta, November 2013)Chris Adamson
 
Introduction to android
Introduction to androidIntroduction to android
Introduction to androidjavalabsf
 
Android Penetration Testing - Day 1
Android Penetration Testing - Day 1Android Penetration Testing - Day 1
Android Penetration Testing - Day 1Mohammed Adam
 

Ähnlich wie Android media-chapter 23 (20)

Android development-tutorial
Android development-tutorialAndroid development-tutorial
Android development-tutorial
 
Android security by ravi-rai
Android security by ravi-raiAndroid security by ravi-rai
Android security by ravi-rai
 
Basic Android
Basic AndroidBasic Android
Basic Android
 
Android media framework overview
Android media framework overviewAndroid media framework overview
Android media framework overview
 
Scoped storage in android 10 all you need to know
Scoped storage in android 10  all you need to knowScoped storage in android 10  all you need to know
Scoped storage in android 10 all you need to know
 
Android application
Android applicationAndroid application
Android application
 
Android For Java Developers
Android For Java DevelopersAndroid For Java Developers
Android For Java Developers
 
Level 3
Level 3Level 3
Level 3
 
03 android application structure
03 android application structure03 android application structure
03 android application structure
 
2.Android Platform_Theory.pptx
2.Android Platform_Theory.pptx2.Android Platform_Theory.pptx
2.Android Platform_Theory.pptx
 
Chapter03 Of It .... BBa 1st
Chapter03 Of It .... BBa 1st Chapter03 Of It .... BBa 1st
Chapter03 Of It .... BBa 1st
 
Android Overview
Android OverviewAndroid Overview
Android Overview
 
How to create android applications
How to create android applicationsHow to create android applications
How to create android applications
 
Designing of Video Player with Python
Designing of Video Player with PythonDesigning of Video Player with Python
Designing of Video Player with Python
 
Get On The Audiobus (CocoaConf Atlanta, November 2013)
Get On The Audiobus (CocoaConf Atlanta, November 2013)Get On The Audiobus (CocoaConf Atlanta, November 2013)
Get On The Audiobus (CocoaConf Atlanta, November 2013)
 
Introduction to android
Introduction to androidIntroduction to android
Introduction to android
 
Software and its types
Software and its typesSoftware and its types
Software and its types
 
Android Penetration Testing - Day 1
Android Penetration Testing - Day 1Android Penetration Testing - Day 1
Android Penetration Testing - Day 1
 
Android cours
Android coursAndroid cours
Android cours
 
Android beginners David
Android beginners DavidAndroid beginners David
Android beginners David
 

Mehr von Dr. Ramkumar Lakshminarayanan

Mehr von Dr. Ramkumar Lakshminarayanan (20)

IT security awareness
IT security awarenessIT security awareness
IT security awareness
 
Basics of IT security
Basics of IT securityBasics of IT security
Basics of IT security
 
IT Security Awareness Posters
IT Security Awareness PostersIT Security Awareness Posters
IT Security Awareness Posters
 
Normalisation revision
Normalisation revisionNormalisation revision
Normalisation revision
 
Windows mobile programming
Windows mobile programmingWindows mobile programming
Windows mobile programming
 
Concurrency control
Concurrency controlConcurrency control
Concurrency control
 
Web technology today
Web technology todayWeb technology today
Web technology today
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
Phonegap for Android
Phonegap for AndroidPhonegap for Android
Phonegap for Android
 
Create and Sell Android App (in tamil)
Create and Sell Android App (in tamil)Create and Sell Android App (in tamil)
Create and Sell Android App (in tamil)
 
Android app - Creating Live Wallpaper (tamil)
Android app - Creating Live Wallpaper (tamil)Android app - Creating Live Wallpaper (tamil)
Android app - Creating Live Wallpaper (tamil)
 
Android Tips (Tamil)
Android Tips (Tamil)Android Tips (Tamil)
Android Tips (Tamil)
 
Android Animation (in tamil)
Android Animation (in tamil)Android Animation (in tamil)
Android Animation (in tamil)
 
Creating List in Android App (in tamil)
Creating List in Android App (in tamil)Creating List in Android App (in tamil)
Creating List in Android App (in tamil)
 
Single Touch event view in Android (in tamil)
Single Touch event view in Android (in tamil)Single Touch event view in Android (in tamil)
Single Touch event view in Android (in tamil)
 
Android Application using seekbar (in tamil)
Android Application using seekbar (in tamil)Android Application using seekbar (in tamil)
Android Application using seekbar (in tamil)
 
Rating Bar in Android Example
Rating Bar in Android ExampleRating Bar in Android Example
Rating Bar in Android Example
 
Creating Image Gallery - Android app (in tamil)
Creating Image Gallery - Android app (in tamil)Creating Image Gallery - Android app (in tamil)
Creating Image Gallery - Android app (in tamil)
 
Create Android App using web view (in tamil)
Create Android App using web view (in tamil)Create Android App using web view (in tamil)
Create Android App using web view (in tamil)
 
Hardware Interface in Android (in tamil)
Hardware Interface in Android (in tamil)Hardware Interface in Android (in tamil)
Hardware Interface in Android (in tamil)
 

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.