Friday, May 4, 2012

Play Ring Tone in Ring Tone Text Transfer Language (RTTTL) format using MediaPlayer


Play Ring Tone in Ring Tone Text Transfer Language (RTTTL) format using MediaPlayer

Ring Tone Text Transfer Language (RTTTL) was developed by Nokia to be used to transfer ringtonesto cellphone by Nokia, to know more please refer to Wikipedia - Ring Tone Transfer Language.

It's a example to play a single note in RTTTL format using MediaPlayer.

Play Ring Tone in Ring Tone Text Transfer Language (RTTTL) format using MediaPlayer

First, create a xml(/res/raw/a4.rtttl) to define a single note in RTTTL format.
<a4:d=4,o=5,b=250:a4;


Main Code:
package com.exercise.AndroidRTTTL;

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

public class AndroidRTTTLActivity extends Activity {
 
 Button buttonPlay;
 MediaPlayer mediaPlayer;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        buttonPlay = (Button)findViewById(R.id.play);
        buttonPlay.setOnClickListener(buttonPlayOnClickListener);
    }
    
    Button.OnClickListener buttonPlayOnClickListener
    = new Button.OnClickListener(){

  @Override
  public void onClick(View arg0) {
   // TODO Auto-generated method stub
   if(mediaPlayer != null) 
   {
    mediaPlayer.release();
   }
   
   mediaPlayer = MediaPlayer.create(AndroidRTTTLActivity.this, R.raw.a4);
   mediaPlayer.start();
   
  }};
}


Layout, main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    <Button
        android:id="@+id/play" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Play" />

</LinearLayout>

No comments: