You are on page 1of 15

Unit-IV

1. Playing Audio and Video in android

Playing audio and video in a mobile application involves several key components and steps.

Key Components:

 Media Player: A media player component is used to handle the playback of audio and video
content. In Android, the MediaPlayer class is commonly used for this purpose.

 Media Resources: You need audio and video files that you want to play. These can be stored
locally on the device or fetched from remote sources.

 User Interface (UI): You'll need a user interface to control the playback, such as play, pause,
stop, seek, and volume controls. This can be done using buttons, seek bars, or other UI
elements.

Steps for Audio and Video Playback:

Step 1: Set Up Permissions

In AndroidManifest.xml file, specify the necessary permissions for audio and video playback, such as
internet access and access to local media files if applicable.

<uses-permission android:name="android.permission.INTERNET" />


<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Step 2: Initialize the Media Player

In Android app code, create and initialize a MediaPlayer instance. Set up the data source (the audio
or video file) for the player.

MediaPlayer mediaPlayer = new MediaPlayer();


mediaPlayer.setDataSource("http://example.com/audio.mp3"); // or setDataSource locally
mediaPlayer.prepare(); // Prepare the media player

Step 3: Implement UI Controls

Create UI elements, such as play, pause, stop, and seek controls, to allow users to interact with the
media player.

<Button
android:id="@+id/playButton"
android:text="Play"
android:onClick="playAudio" />
<Button
android:id="@+id/pauseButton"
android:text="Pause"
android:onClick="pauseAudio" />

Step 4: Define Playback Actions


In Android code, define actions for the UI controls. For example, when the "Play" button is clicked,
media starts playing.

public void playAudio(View view) {


if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
Step 5: Release Resources

After playback is completed or the app is closed, release the media player and associated resources.

@Override
protected void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
mediaPlayer.release();
}
}
Step 6: Error Handling and Playback Control

Handle errors, implement playback control features (e.g., seek, volume control), and manage the
media player's state according to user interactions.

Example:Playing Audio in Android

MainActivity.java

import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {


Button start,pause,stop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

start=(Button)findViewById(R.id.button1);
pause=(Button)findViewById(R.id.button2);
stop=(Button)findViewById(R.id.button3);
//creating media player
final MediaPlayer mp=new MediaPlayer();
try{
//you can change the path, here path is external directory(e.g. sdcard) /Music/maine.mp3
mp.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/Music/maine.mp3");

mp.prepare();
}catch(Exception e){e.printStackTrace();}

start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mp.start();
}
});
pause.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mp.pause();
}
});
stop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mp.stop();
}
});
}
}

2. Integrating Camera Functionality into a Mobile App to Capture Pictures:


Camera is mainly used to capture picture and video. We can control the camera by using methods of
camera api. Android provides the facility to work on camera by 2 ways:
 By Camera Intent
 By Camera API

Basic classes of Camera Intent and API


There are mainly four classes.

1. Intent
By the help of 2 constants of MediaStore class, we can capture picture and video without
using the
ACTION_IMAGE_CAPTURE
ACTION_VIDEO_CAPTURE
2. Camera
It is main class of camera api, that can be used to take picture and video.

3. SurfaceView
It represents a surface view ore preview of live camera.

4. MediaRecorder
It is used to record video using camera. It can also be used to record audio files as we have
seen in the previous example of media frameworkinstance of Camera class.

Activity_main.xml
<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Take a Photo" >
</Button>

<ImageView
android:id="@+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="@+id/button1"
android:layout_alignParentTop="true"
android:src="@drawable/ic_launcher" >
</ImageView>
</RelativeLayout>
MainActivity.java

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {


private static final int CAMERA_REQUEST = 1888;
ImageView imageView;
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

imageView = (ImageView) this.findViewById(R.id.imageView1);


Button photoButton = (Button) this.findViewById(R.id.button1);

photoButton.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {


if (requestCode == CAMERA_REQUEST) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}
3. Media Recording in Android
MediaRecorder class can be used to record audio and video files.

After recording the media, we can create a sound file that can be played later.

In this example, we are going to record the audio file and storing it in the external directory
in 3gp format.

activity_main.xml
Drag 2 buttons from the pallete, one to start the recording and another stop the recording.
Here, we are registering the view with the listener in xml file using android:onClick.

<RelativeLayout xmlns:androclass="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" >

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="68dp"
android:layout_marginTop="50dp"
android:text="Start Recording"
android:onClick="startRecording"
/>

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"
android:layout_marginTop="64dp"
android:text="Stop Recording"
android:onClick="stopRecording"
/>

</RelativeLayout>

MainActivity.java
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {


MediaRecorder recorder;
File audiofile = null;
static final String TAG = "MediaRecording";
Button startButton,stopButton;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton = (Button) findViewById(R.id.button1);
stopButton = (Button) findViewById(R.id.button2);
}

public void startRecording(View view) throws IOException {


startButton.setEnabled(false);
stopButton.setEnabled(true);
//Creating file
File dir = Environment.getExternalStorageDirectory();
try {
audiofile = File.createTempFile("sound", ".3gp", dir);
} catch (IOException e) {
Log.e(TAG, "external storage access error");
return;
}
//Creating MediaRecorder and specifying audio source, output format, encoder &
output format
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(audiofile.getAbsolutePath());
recorder.prepare();
recorder.start();
}

public void stopRecording(View view) {


startButton.setEnabled(true);
stopButton.setEnabled(false);
//stopping recorder
recorder.stop();
recorder.release();
//after stopping the recorder, create the sound file and add it to media library.
addRecordingToMediaLibrary();
}

protected void addRecordingToMediaLibrary() {


//creating content values of size 4
ContentValues values = new ContentValues(4);
long current = System.currentTimeMillis();
values.put(MediaStore.Audio.Media.TITLE, "audio" + audiofile.getName());
values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/3gpp");
values.put(MediaStore.Audio.Media.DATA, audiofile.getAbsolutePath());

//creating content resolver and storing it in the external content uri


ContentResolver contentResolver = getContentResolver();
Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Uri newUri = contentResolver.insert(base, values);

//sending broadcast message to scan the media file so that it can be available
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, newUri));
Toast.makeText(this, "Added File " + newUri, Toast.LENGTH_LONG).show();
}
}
Unit-IV

4. Sending SMS:

W//Getting intent and PendingIntent instance

Intent intent=new Intent(getApplicationContext(),MainActivity.class);

PendingIntent pi=PendingIntent.getActivity(getApplicationContext(), 0, intent,0);

//Get the SmsManager instance and call the sendTextMessage method to send message

SmsManager sms=SmsManager.getDefault();

sms.sendTextMessage(“9876543210", null, "hello world", pi,null); e can send sms in android via
intent.

Example of sending sms in android

activity_main.xml

Drag the 2 edittexts, 2 textviews and 1 button from the pallete, now the activity_main.xml file will
like this:

activity_main.xml
<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="20dp"
android:ems="10" />

<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="26dp"
android:ems="10"
android:inputType="textMultiLine" />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText1"
android:layout_alignBottom="@+id/editText1"
android:layout_toLeftOf="@+id/editText1"
android:text="Mobile No:" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText2"
android:layout_alignBottom="@+id/editText2"
android:layout_alignLeft="@+id/textView1"
android:text="Message:" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText2"
android:layout_below="@+id/editText2"
android:layout_marginLeft="34dp"
android:layout_marginTop="48dp"
android:text="Send SMS" />

</RelativeLayout>

Write the permission code in Android-Manifest.xml file


<uses-permission android:name="android.permission.SEND_SMS"/>

MainActivity.java
package com.example.sendsms;

import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.telephony.SmsManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

EditText mobileno,message;
Button sendsms;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mobileno=(EditText)findViewById(R.id.editText1);
message=(EditText)findViewById(R.id.editText2);
sendsms=(Button)findViewById(R.id.button1);

//Performing action on button click


sendsms.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
String no=mobileno.getText().toString();
String msg=message.getText().toString();

//Getting intent and PendingIntent instance


Intent intent=new Intent(getApplicationContext(),MainActivity.class);
PendingIntent pi=PendingIntent.getActivity(getApplicationContext(), 0, intent,0);

//Get the SmsManager instance and call the sendTextMessage method to send message
SmsManager sms=SmsManager.getDefault();
sms.sendTextMessage(no, null, msg, pi,null);
Toast.makeText(getApplicationContext(), "Message Sent successfully!",
Toast.LENGTH_LONG).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.activity_main, menu);
return true;
}

Making Phone calls in android:


We are able to make a phone call in android via intent.

Intent callIntent = new Intent(Intent.ACTION_CALL);


callIntent.setData(Uri.parse("tel:"+8802177690));//change the number
startActivity(callIntent);

activity_main.xml
<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="118dp"
android:text="Call" />

<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:ems="10" />

</RelativeLayout>

Write the permission code in Android-Manifest.xml file


You need to write CALL_PHONE permission as given below:

<uses-permission android:name="android.permission.CALL_PHONE" />

MainActivity.java
package com.example.phonecall;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {


EditText edittext1;
Button button1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//Getting the edittext and button instance


edittext1=(EditText)findViewById(R.id.editText1);
button1=(Button)findViewById(R.id.button1);

//Performing action on button click


button1.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
String number=edittext1.getText().toString();
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+number));
startActivity(callIntent);
}

});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

You might also like