How to play Audio , pause , stop by media player from internal storage URL or raw audio file in android studio
playing Audio is most common task in app we are using a row audio file into app to play or control audio you can use your own URL rather then raw file URL in android studio
Step 1: create a video view in to xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="fun_btnplay"
android:text="paly"></Button>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="fun_btnpause"
android:text="pause"></Button>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="fun_btnstop"
android:text="stop"></Button>
</LinearLayout>
Step 2:add Audio file into raw folder or use internal storage URI
Step 3:set on button click to play video from raw folder or use your internal storage
MediaPlayer player;
public void fun_btnplay(View view) {
if (player == null) {
player = MediaPlayer.create(this, R.raw.song);
player.setVolume(20, 40);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
float duration = player.getDuration();
Toast.makeText(this, String.valueOf(duration), Toast.LENGTH_SHORT).show();
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
stoplayer();
}
});
}
player.start();
}
public void fun_btnpause(View view) {
if (player != null) {
player.pause();
}
}
public void fun_btnstop(View view) {
stoplayer();
}
private void stoplayer() {
if (player != null) {
player.release();
player = null;
Toast.makeText(this, "Stop Music", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onStop() {
super.onStop();
stoplayer();
}
Comments
Post a Comment