Archive

Archive for February, 2009

Android Audio Support

February 13th, 2009

Android support Media API as optional APIs. The media APIs provide functionality of playing and recording audio files and video files. In today’s post we will see how to play and record audio files.

Playing Audio File:
Android has defined a MediaPlayer class for playing media file. This class can be used to play the audio files. The class provides static methods to create the instance of the media player. Here is how the MediaPlayer object can be obtained using create methods

MediaPlayer.create(context, Uri.parse("file:///sdcard/audio_file.mp3");

and

MediaPlayer.create(context, R.raw.song_file);

The first create methods gets the Uri for the audio file and can be used to play files present on the phone sdcard. The second create method use the application resource file song_file.mp3. The song_file.mp3 file is added as a raw resource under res/raw directory.
Note that if the MediaPlayer object does not get created successfully, the create methods will return null so it will be better to check for the return object for null value to avoid NullPointer exception.

The MediaPlayer object can also be obtained by instantiating using MediaPlayer constructor. The object created like this has to be initialized with the file that needs to be played. setDataSource() method can be used to initialize the object with the audio file.

MediaPlayer mediaPlayer = new MediaPlayer();

try {
mediaPlayer.setDataSource("/sdcard/audio_file.mp3"); // provide path to the file.
} catch (IllegalArgumentException e) {
// handle exception
} catch (IllegalStateException e) {
// handle exception
} catch (IOException e) {
// handle exception
}

If you want to send the media player object with one of the files from application raw resources or from application assets files you can do that as follows:

try {
AssetFileDescriptor fd = getResources().openRawResouceFd(R.raw.song_file);
mediaPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
fd.close();
} catch (IllegalArgumentException e) {
// handle exception
} catch (IllegalStateException e) {
// handle exception
} catch (IOException e) {
// handle exception
}

The MediaPlayer object has to be prepared before the player can start playing the song. The prepare() method is the blocking method and blocks until the media player is ready to play the song. One non blocking method prepareAsync() is also provided. The non blocking prepare method should be used in case media player is used to play a song from a stream and need to buffer data before song can be played. The create methods that we saw earlier call the prepare() method and application must not call it again. To start file playback use start() method. This is how you play a file:

MediaPlayer mediaPlayer = new MediaPlayer();

try {
mediaPlayer.setDataSource("/sdcard/audio_file.mp3"); // provide path to the file.
mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
// handle exception
} catch (IllegalStateException e) {
// handle exception
} catch (IOException e) {
// handle exception
}

mediaPlayer.start();

The file playback can be pause with pause() method, and can be resumes with start method. The file playback can be stopped with stop() method. The media player object has to reset before it can be setup for some other song file. The media player object has to be released after its use.

Android Media API defines some listeners like OnCompletionListener, OnPrepareListener, OnErrorListener, OnBufferingUpdateListener
OnCompletionListener event gets fired when media player complete the playing of the current audio file. You can use this listener event for playing next song from the list or releasing the media player object.

OnPrepareListener is needed when prepareAsync method is used. Since the prepareAsync method does not block for the call duration, the application can not start playing the song. The onPrepared() event function will be called once the media player is ready. You can start playing the song in the onPrepared() method.

OnErrorListener is also used in case of asynchronous operations. If any error occurs in asynchronous operation, onError() method of this listener will be called.

Recording Audio Files:

The Media API also provides functionality to record audio files. The MediaRecorder class can be used for media recording. The MediaRecorder has to be initialized with the Audio Encoder, output format (codec to be used for recorded file), Audio Source (like Microphone) and output file path where the recorded file will be stored. Here is how recording can be done:

MediaRecorder recorder = new MediaRecorder();

recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

recorder.setOutputFile(filePath); // complete file path

recorder.prepare(); recorder.start();

This will start the recording the recording can be stored with stop() method. The MediaRecorder object also needs to be release after its use.
That all for today’s post. We will see Media APIs Video support in some other post.

Android, Android API , , , , ,

Android Basics – Alarm Service

February 3rd, 2009

Today we will see Alarm Service provided by Android. Android provide AlarmManager class. The class provides access to the android Alarm Service. AlarmManager provide the methods to set the alarms. Alarm can be one time or repeating. When the alarms goes off (alarm time occurs) a pending intent will be broadcasted that can invoke a BroadCastReceiver (intent receiver) or Service or Activity.

Let’s see how to set alarms. The Alarm Manger instance for the Alarm service can be obtained as follows:

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

There are 4 types of alarms the AlarmManager has defined constants for each type as RTC, RTC_WAKEUP, ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP.

While setting an alarm, a pending intent has to be defined. The pending intent is called when alarm goes off.
One time alarms:
One time alarm can be set using AlarmManager set() method. Here is how it can be done:

Intent intent = new Intent(this, OnetimeAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, intent, 0);

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), sender);
Toast.makeText(this, "Alarm set", Toast.LENGTH_LONG).show();

The pending intent is created for a Broadcast Receiver, the receiver is just notifying the user using Toast. The alarm is set to 10 secs from current time. Here is the code for the intent receiver:

public class OnetimeAlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();
}
}

Repeating alarm:
Setting a repeating alarm is similar to setting one time alarm. The repeating alarm can be set using setRepeating() method of AlarmManager. Here is the code:

Intent intent = new Intent(this, RepeatingAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, intent, 0);

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), 10 * 1000, pendingIntent);
Toast.makeText(this, "Alarm set", Toast.LENGTH_LONG).show();

There is only one parameter extra in case of repeating alarm. The repeating alarm takes interval after which the alarm should be repeated. In this case the alarm is repeating itself after 10 secs.

The code of the RepeatingAlarmReceiver is:

public class RepeatingAlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Repeating Alarm worked.", Toast.LENGTH_LONG).show();
}
}

The repeating alarms have to be cancelled to stop them. AlarmManager provide a cancel() method that requires the same intent class with which the intent is created. This is how you can cancel the alarm.

alarmManager.cancel(pendingIntent);

Note the pendingIntent object does not need to be same object. The intent fields like action, class, category etc should be same while creating the alarm. The intent is used to identify the alarm to cancel it.

E.g. Alarm Clock:
You can create a wake up alarm with the help of android Alarm service and notification service. The ring tone and the vibration pattern can be put in the intent of extras that can be retrieved by the Broadcast receiver. The code will be as follows:

Intent intent = new Intent(this, RepeatingAlarmReceiver.class);

intent.putExtra("Ringtone", Uri.parse("file:///sdcard/audiofile.mp3"));
intent.putExtra("vibrationPatern", new long[] { 200, 300 });
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), (24 * 60 * 60 * 1000), pendingIntent);

The alarm is set as daily (will repeat after 24 hours). The broadcast receiver can show a notification with the help of the notification service.

NotificationManager manger = (NotificationManager)     context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon, "Wake up alarm", System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
notification.setLatestEventInfo(context, "Context Title", "Context text", contentIntent);
notification.flags = Notification.FLAG_INSISTENT;

notification.sound = (Uri) intent.getParcelableExtra("Ringtone");
notification.vibrate = (long[]) intent.getExtras().get("vibrationPatern");

// The PendingIntent to launch our activity if the user selects this notification
manger.notify(NOTIFICATION_ID, notification);

You can set appropriate values for contentIntent as your need. You can also pass an array of boolean for each day like Sunday, Monday etc. The intent receiver will match the current day with the alarm days and show the alarm notification accordingly.

Android API , , , ,