Android,
A Complete Course, From
Basics to Enterprise Edition
Android, A Complete Course, From Basics to Enterprise
Edition
Multimedia et Appareil photographique.
1.1 Les fichiers Multimédia et l’appareil photo
Cet
article est extraie du livre « Android, A Complete Course »,
disponible sur Android2ee.com.
Les
exemples ou les programmes présents dans cet ouvrage sont fournis pour
illustrer les descriptions théoriques. Ce code est libre de toute utilisation
mais n'est pas distribuable.
La
distribution du code est reservée au site :
La
propriété intellectuelle du code appartient à :
L’utilisation
de ces codes est sous votre unique responsabilité et personne d’autre que vous
ne pourra être tenu responsable des préjudices ou dommages de quelques natures
que ce soit pouvant résulter de son utilisation.
Tous
les noms de produits ou marques cités dans cet ouvrage sont des marques déposés
par leurs propriétaires respectifs.
Publié par http://android2ee.com
Titre Original : Android, A Complete Course, From
Basics to Enterprise Edition. Édition Française.
ISBN : 979-10-90388-00-0
Copyright © 2011 by Mathias Séguy
Aucune
représentation ou reproduction, même partielle, autre que celles prévues à
l’article L. 122-5 2° et 3° a) du code de la propriété intellectuelle ne peut
être faite sans l’autorisation expresse de Mathias Seguy ou, le cas échéant,
sans le respect des modalités prévues à l’article L. 122-10 dudit code
Vous pouvez trouver la liste des types de fichiers supportés par Android à la page suivante : http://developer.android.com/guide/appendix/media-formats.html
Le mediaPlayer suit les étapes suivantes :
· Initialisation avec le fichier à lire,
· Préparation à la lecture,
· Démarrage de la lecture,
· Mise en pause ou arrêt utilisateur,
· Fin de la lecture,
· Libération mémoire : appel de la méthode release.
Dans votre Layout.xml, vous devez rajouter votre vue pour afficher les vidéos :
<VideoView android:id="@+id/VideoView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></VideoView>
Dans votre code Java :
/****************************************************************************************/
/**
Audio Playing **************************************************************************/
/****************************************************************************************/
//Retrieve
the Context:
Context
applicationContext=getApplicationContext();
//INITIALISATION
//-------------
//Finding
the ressource
//A
raw ressource
String
rawRessource="R.raw.myAudioFile";
//An
external ressource on the sd card
String
fileRessource="file://sdcard/myAudioFile.mp3";
//A web ressource
String
urlRessource="http://mySite/myAudioFile.mp3";
//A system ressource
String
systemRessource="Settings.System.DEFAULT_RINGTONE_URI";
//You can use any of those URI to initilialize the player
MediaPlayer
mediaPlayer=MediaPlayer.create(applicationContext, Uri.parse(fileRessource));
//Change the ressource once the MediaPlayer have been created
try {
mediaPlayer.setDataSource(rawRessource);
//And always call the prepare method
mediaPlayer.prepare();
}
catch
(IllegalArgumentException e) {
e.printStackTrace();
}
catch
(IllegalStateException e) {
e.printStackTrace();
}
catch
(IOException e) {
e.printStackTrace();
}
//Managing the player
//-------------------
//Start the play
mediaPlayer.start();
//Pause
mediaPlayer.pause();
//Stop
mediaPlayer.stop();
//Moving inside the file:
//Retrieve the current position in milliSeconds
int
position=mediaPlayer.getCurrentPosition();
//Retrieve the duration in milliSeconds
int
duration=mediaPlayer.getDuration();
//Define a target to move:
int
targetPosition=position/2;
//Move to that target
mediaPlayer.seekTo(targetPosition);
//Define the looping parameter
mediaPlayer.setLooping(!mediaPlayer.isLooping());
//manage the volume, the volume is a float between 0.0f(min) and
1.0f(max)
float
leftVolume=0.5f;
float
rightVolume=0.5f;
mediaPlayer.setVolume(leftVolume,
rightVolume);
//Give back memory when you have finished
mediaPlayer.release();
/*****************************************************************************************/
/** Video Player **************************************************************************/
/*****************************************************************************************/
//Using a VideoView
VideoView
videoView=(VideoView)findViewById(R.id.VideoView);
//An external ressource on the sd card
String
videoLocalFile="/sdcard/myVideoFile.mp4";
String
videoLocalUriFile="file:///sdcard/myVideoFile.mp4";
Uri
videoLocalUri=Uri.parse(videoLocalUriFile);
//A web ressource
String
videoHttpFile="http://mySite/myVideoFile.mp4";
//Then you can set your videao using its path
videoView.setVideoPath(videoLocalFile);
//Or using the URI of the video file:
videoView.setVideoURI(Uri.parse(videoHttpFile));
//You can set the screen to remain on
videoView.setKeepScreenOn(true);
//Launch the video:
videoView.start();
//Or make a pause
videoView.pause();
//or stop it
videoView.stopPlayback();
//or find some information on the file
//Retrieve the current position in milliSeconds
position=videoView.getCurrentPosition();
//Retrieve the duration in milliSeconds
duration=videoView.getDuration();
//or move
if(videoView.canSeekForward()){
//then move forward
targetPosition=position+((duration-position)/2);
videoView.seekTo(targetPosition);
}else if(videoView.canSeekBackward()){
//then move backward
videoView.seekTo(position/2);
}
Pour enregistrer une photographie ou une vidéo, vous pouvez utiliser les activités natives d’Android en les appelant au moyen d’intentions. Il vous faut ensuite surcharger la méthode onActivtyResult pour récupérer votre image ou votre vidéo.
/**
* The id of the request code
associated to the call of the Intent Image_Capture
*/
private final int recordPictureMyIntentId=11021974;
/**
* The id of the request code
associated to the call of the Intent Video_Capture
*/
private final int recordVideoMyIntentId=13121974;
/**
* The recording method exemple
*/
private void
recording(){
/******************************************************************************/
/** Picture recording
***************************************************************/
/*******************************************************************************/
//Shortcut some android constant
final
int
HighQuality=1;
final
int
lowQuality=0;
//Define the Intent to launch for
calling a picture record
Intent recordPictureIntent=new
Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//Define the URI you want your picture
to be store
Uri outPutUri=Uri.parse("file:///sdcard/myFilePath/myFileName");
//Then add extra information on the
Intent:
//Where to store the file
recordPictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
outPutUri);
//What is picture quality expected
recordPictureIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,HighQuality);
//And launch the Intent
startActivityForResult(recordPictureIntent,
recordPictureMyIntentId);
//-------------------------------------------------------------
//!\\To take only a thumbnail, just
forget to define the output
//-------------------------------------------------------------
/*********************************************************************************/
/** Video Recorder
******************************************************************/
/*********************************************************************************/
//Define the Intent to launch for
calling a picture record
Intent recordVideoIntent=new
Intent(MediaStore.ACTION_VIDEO_CAPTURE);
//Define the URI you want your picture
to be store
Uri outPutVideoUri=Uri.parse("file:///sdcard/myFilePath/myFileName");
//Then add extra information on the
Intent:
//Where to store the file
recordVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT,
outPutVideoUri);
//What is picture quality expected
recordVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,HighQuality);
//And launch the Intent
startActivityForResult(recordVideoIntent, recordVideoMyIntentId);
}
/*
(non-Javadoc)
* @see
android.app.Activity#onActivityResult(int, int, android.content.Intent)
*/
@Override
protected void
onActivityResult(int
requestCode, int
resultCode, Intent data) {
if(requestCode==recordPictureMyIntentId){
//Thumbnail case:
if(data!=null){
if(data.hasExtra("data")){
//Get the thumbnail Bitmap picture
Bitmap thumbnail=data.getParcelableExtra("data");
}
}else{
//A real picture case:
//Your picture is store in the ouput uri
you have defined, you can do something with it
}
}else if(requestCode==recordVideoMyIntentId){
//Normally, your video should be in the
output uri you defined
Uri recordedVideo=data.getData();
}
}
Le chapitre 7.1.5.2 La classe MediaStore explique comment utiliser le MediaStore qui est un content provider comme un autre.
Pour l’enregistrement de vidéo, la classe Media Recorder à utiliser.
Pour l’enregistrement audio, aussi (cf. http://developer.android.com/guide/topics/media/index.html)
Pour la manipulation de l’appareil photo, la classe Camera est celle à utiliser.
Dans le cas de la vidéo ou de la photo, pour pré-visualiser il vous faut un objet appelé SurfaceView. Vous le déclarez dans votre Layout.xml comme une vue usuelle et le récupérez dans votre code java comme un composant graphique normal. Dans votre méthode onCreate appelez surface.getHolder().addCallBack(this). Votre activité doit implémenter l’interface SurfaceHolder.CallBack et sa méthode surfaceCreated qui reçoit en paramètre un holder qui n’est autre que celui de Surface que vous avez déclaré dans onCreate.