Play mp3 file within a service : Mp3 « Media « Android






Play mp3 file within a service

 

package app.test;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

class Music extends Service {
    private MediaPlayer player;

  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }
  
  public void onStart(Intent intent, int startId) {       
        super.onStart(intent, startId);
        player = MediaPlayer.create(this, R.raw.mp3File);
        player.start();
    }
   
    public void onDestroy() {
        super.onDestroy();
        player.stop();
    }
}

public class Test extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button button1 = (Button)findViewById(R.id.start);
        button1.setOnClickListener(startIt);
        Button button2 = (Button)findViewById(R.id.stop);
        button2.setOnClickListener(stopIt);
    }
    
    private OnClickListener startIt = new OnClickListener()
    {
        public void onClick(View v)
        {           
            startService(new Intent("app.test.Test.START_AUDIO_SERVICE"));
        }
    };
   
    private OnClickListener stopIt = new OnClickListener()
    {
        public void onClick(View v)
        {
            stopService(new Intent("app.test.Test.START_AUDIO_SERVICE"));
            finish();           
        }
    };
}

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
    
    <Button
    android:id="@+id/start"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Start Play"   
    />
    
    <Button
    android:id="@+id/stop"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Stop Play"   
    />
    
</LinearLayout>

   
  








Related examples in the same category

1.Mp3 Player
2.Async Mp3 Player Demo
3.Play Mp3 file from a Url
4.Load Mp3 file from local file system