Monday, April 25, 2022

Android Media Player with Buffer progress and play position

 Step 1 : Android XML File : activity_audio_streaming.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
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">

<Button android:id="@+id/audioStreamBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="70dp"
android:textSize="18sp"
android:text="Start Streaming"
android:layout_centerHorizontal="true"/>

<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="3">

<TextView android:id="@+id/current_audio_duration"
android:layout_width="0dp"
android:text="10:11"
android:layout_weight="0.5"
android:layout_height="wrap_content"/>
<SeekBar
android:layout_weight="2"
android:id="@+id/seekbar"
android:layout_width="0dp"
android:layout_height="wrap_content"/>

<TextView android:id="@+id/current_audio_remaing"
android:layout_width="0dp"
android:text="10:11" android:layout_weight="0.5"
android:layout_height="wrap_content"/>

</LinearLayout>

</RelativeLayout>

Step 2 : Java File AudioStreamingActivity.Java

public class AudioStreamingActivity extends AppCompatActivity {
private Button btn;
private boolean playPause;
private MediaPlayer mediaPlayer;
private ProgressDialog progressDialog;
private boolean initialStage = true;
SeekBar seekbar;
TextView current_audio_duration, current_audio_remaing;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_streaming);

btn = findViewById(R.id.audioStreamBtn);
seekbar = findViewById(R.id.seekbar);
current_audio_remaing = findViewById(R.id.current_audio_remaing);
current_audio_duration = findViewById(R.id.current_audio_duration);

mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
progressDialog = new ProgressDialog(this);

mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent)
{
double ratio = percent / 100.0;
int bufferingLevel = (int)(mp.getDuration() * ratio);
seekbar.setSecondaryProgress(bufferingLevel);
}

});

btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!playPause) {
btn.setText("Pause Streaming");

if (initialStage) {
new Player().execute("https://pagalworld3.org/14642/Aafat%20Waapas%20-%20Naezy.mp3"); //Add your Media Link
} else {
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
}

playPause = true;

} else {
btn.setText("Launch Streaming");

if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}

playPause = false;
}
}
});
}

@Override
protected void onPause() {
super.onPause();

if (mediaPlayer != null) {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}
}

class Player extends AsyncTask<String, Void, Boolean> {
@Override
protected void onProgressUpdate(Void... values) {
seekbar.setProgress(mediaPlayer.getCurrentPosition());

super.onProgressUpdate(values);
}

@Override
protected Boolean doInBackground(String... strings) {
Boolean prepared = false;

try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
initialStage = true;
playPause = false;
btn.setText("Launch Streaming");
mediaPlayer.stop();
mediaPlayer.reset();
}
});

mediaPlayer.prepare();
prepared = true;

seekHandler.postDelayed(updateSeekBar, 15);

} catch (Exception e) {
Log.e("MyAudioStreamingApp", e.getMessage());
prepared = false;
}

return prepared;
}

@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);

if (progressDialog.isShowing()) {
progressDialog.cancel();
}

mediaPlayer.start();
seekbar.setMax(mediaPlayer.getDuration());
initialStage = false;
}

@Override
protected void onPreExecute() {
super.onPreExecute();

progressDialog.setMessage("Buffering...");
progressDialog.show();
}
}

Handler seekHandler = new Handler();
private Runnable updateSeekBar = new Runnable() {
public void run() {
long totalDuration = mediaPlayer.getDuration();
long currentDuration = mediaPlayer.getCurrentPosition();

// Displaying Total Duration time
Log.d("time ", "data " + milliSecondsToTimer(totalDuration - currentDuration));
// Displaying time completed playing
Log.d("time ", "data " + milliSecondsToTimer(currentDuration));
current_audio_remaing.setText(milliSecondsToTimer(totalDuration - currentDuration) + "");
current_audio_duration.setText(milliSecondsToTimer(currentDuration) + "");

// Updating progress bar
seekbar.setProgress((int) currentDuration);

// Call this thread again after 15 milliseconds => ~ 1000/60fps
seekHandler.postDelayed(this, 15);
}
};

/**
* Function to convert milliseconds time to
* Timer Format
* Hours:Minutes:Seconds
*/
public String milliSecondsToTimer(long milliseconds) {
String finalTimerString = "";
String secondsString = "";

// Convert total duration into time
int hours = (int) (milliseconds / (1000 * 60 * 60));
int minutes = (int) (milliseconds % (1000 * 60 * 60)) / (1000 * 60);
int seconds = (int) ((milliseconds % (1000 * 60 * 60)) % (1000 * 60) / 1000);
// Add hours if there
if (hours > 0) {
finalTimerString = hours + ":";
}

// Prepending 0 to seconds if it is one digit
if (seconds < 10) {
secondsString = "0" + seconds;
} else {
secondsString = "" + seconds;
}

finalTimerString = finalTimerString + minutes + ":" + secondsString;

// return timer string
return finalTimerString;
}

}

Step 3 : Menifest File

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.myapplication">

<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<activity android:name=".AudioStreamingActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>

<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>

No comments:

Post a Comment