This post describes how to start a Service and stop a Service on Button click.
Create your layout in activity_main.xml. Add a Button button1 to pick audio file, another Button button2 to play audio file, a SeekBar to display the duration of song played, and two TextViews to display the duration and name of audio file.
XML
x
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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:text="PICK FILE"
app:layout_constraintBottom_toTopOf="@+id/linear1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:id="@+id/linear1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:background="#ffffdd"
android:gravity="center_horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView2"
android:textSize="18dp"
android:text="Title"/>
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/seekbar1"
android:max="100"
android:padding="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView3"
android:textSize="20dp"
android:padding="10dp"
android:text="00:00 / 00:00"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PLAY"
android:id="@+id/button2"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
In MainActivity.java add following code.
Java
package com.example.pickfile;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioAttributes;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
TextView textview2;
TextView textview3;
Button button1;
Button button2;
SeekBar seekbar1;
String duration;
MediaPlayer mediaPlayer;
ScheduledExecutorService timer;
public static final int PICK_FILE =99;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = findViewById(R.id.button1);
button2 = findViewById(R.id.button2);
textview2 = findViewById(R.id.textView2);
textview3 = findViewById(R.id.textView3);
seekbar1 = findViewById(R.id.seekbar1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("audio/*");
startActivityForResult(intent, PICK_FILE);
}
});
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()){
mediaPlayer.pause();
button2.setText("PLAY");
timer.shutdown();
} else {
mediaPlayer.start();
button2.setText("PAUSE");
timer = Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(new Runnable() {
public void run() {
if (mediaPlayer != null) {
if (!seekbar1.isPressed()) {
seekbar1.setProgress(mediaPlayer.getCurrentPosition());
}
}
}
}, 10, 10, TimeUnit.MILLISECONDS);
}
}
}
});
seekbar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mediaPlayer != null){
int millis = mediaPlayer.getCurrentPosition();
long total_secs = TimeUnit.SECONDS.convert(millis, TimeUnit.MILLISECONDS);
long mins = TimeUnit.MINUTES.convert(total_secs, TimeUnit.SECONDS);
long secs = total_secs - (mins*60);
textview3.setText(mins + ":" + secs + " / " + duration);
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
if (mediaPlayer != null) {
mediaPlayer.seekTo(seekbar1.getProgress());
}
}
});
button2.setEnabled(false);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_FILE && resultCode == RESULT_OK){
if (data != null){
Uri uri = data.getData();
createMediaPlayer(uri);
}
}
}
public void createMediaPlayer(Uri uri){
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioAttributes(
new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build()
);
try {
mediaPlayer.setDataSource(getApplicationContext(), uri);
mediaPlayer.prepare();
textview2.setText(getNameFromUri(uri));
button2.setEnabled(true);
int millis = mediaPlayer.getDuration();
long total_secs = TimeUnit.SECONDS.convert(millis, TimeUnit.MILLISECONDS);
long mins = TimeUnit.MINUTES.convert(total_secs, TimeUnit.SECONDS);
long secs = total_secs - (mins*60);
duration = mins + ":" + secs;
textview3.setText("00:00 / " + duration);
seekbar1.setMax(millis);
seekbar1.setProgress(0);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
releaseMediaPlayer();
}
});
} catch (IOException e){
textview2.setText(e.toString());
}
}
public String getNameFromUri(Uri uri){
String fileName = "";
Cursor cursor = null;
cursor = getContentResolver().query(uri, new String[]{
MediaStore.Images.ImageColumns.DISPLAY_NAME
}, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
fileName = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DISPLAY_NAME));
}
if (cursor != null) {
cursor.close();
}
return fileName;
}
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
}
public void releaseMediaPlayer(){
if (timer != null) {
timer.shutdown();
}
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
button2.setEnabled(false);
textview2.setText("TITLE");
textview3.setText("00:00 / 00:00");
seekbar1.setMax(100);
seekbar1.setProgress(0);
}
}
Now run the app.