Playing Online Videos one by one - java

I have an xml file with videoview:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/back"
android:orientation="vertical"
android:screenOrientation="landscape">
<VideoView
android:id="#+id/videoview_concept"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
And My java part is:
public class playvideos extends Activity implements OnCompletionListener{
public Integer index_val=0;
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
index_val++;
VideoView videoview= (VideoView)findViewById(R.id.videoview_concept);
checkdbconn();
videoview.setVideoURI(Uri.parse(prepare.txtLectureFileName[index_val]));
videoview.setMediaController(new MediaController(this));
videoview.requestFocus();
videoview.start();
}
public void playvideo(View view){
setContentView(R.layout.playvid);
VideoView videoview= (VideoView)findViewById(R.id.videoview_concept);
Log.i("Video URL",videourl_array[index_val]);
checkdbconn();
videoview.setVideoURI(Uri.parse(videourl_array[index_val]));
videoview.setMediaController(new MediaController(this));
videoview.requestFocus();
checkdbconn();
videoview.start();
}
The above code is a button click event. It works really well. If one first video finished, it should automatically play the second video. Thus I want to play all the videos in that array continuously. How to achieve this? Please help me out:)

At last I found out how to play all videos which urls are stored in an array. When I play the video sometimes it plays two videos one by one and sometimes only one video was playing.
This is how I over come this problem. Thanks to #Kirit.
public void playvideos_all(){
videoview.setVideoURI(Uri.parse(prepare.txtLectureFileName[index_val]));
videoview.setMediaController(new MediaController(this));
videoview.requestFocus();
videoview.start();
videoview.setClickable(true);
index_val++;
if(index_val>=no_of_videos){
Toast.makeText(getApplicationContext(), "Videos are finished index: "+index_val+"no of videos:"+no_of_videos, Toast.LENGTH_LONG).show();
}
else{
videoview.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion (MediaPlayer mp) {
mp.stop();
videoview.stopPlayback();
videoview.suspend();
playvideos_all();
}
});
}
}

public class MainActivity extends Activity implements OnCompletionListener{
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
// play next video
}
}

Related

How can I control the media player with service?

I am new to coding and at this point, I made a media player that starts and pauses the audio, has a working seekbar, duration, etc. Now I faced a big issue. The audio can't be played in the background and I found out that I can do this with service but this changes things. I read all kinds of topics on how to control the audio in service with seekbar and all kinds of stuff but nothing helped me. The main problem I face is having the seekbar to control the audio and a text to read the time. If there is someone to help me find a code for this it would be much appreciated.
The layout:
<SeekBar
android:id="#+id/seekBarMusic1"
android:layout_width="match_parent"
android:layout_height="#dimen/_20sdp"
android:layout_marginTop="#dimen/_12sdp"
android:layout_marginLeft="#dimen/_20sdp"
android:layout_marginRight="#dimen/_20sdp"
app:layout_constraintTop_toBottomOf="#+id/cardView"
tools:layout_editor_absoluteX="10dp" />
<TextView
android:id="#+id/playerPositionMusic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00:00"
android:textColor="#color/remain_black"
android:textSize="25dp"
android:layout_marginBottom="#dimen/_80sdp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="#+id/cardView"
app:layout_constraintTop_toBottomOf="#+id/seekBarMusic1" />
<TextView
android:id="#+id/text_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/_80sdp"
android:text="15:00"
android:textColor="#color/remain_black"
android:textSize="25dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/cardView"
app:layout_constraintTop_toBottomOf="#+id/seekBarMusic1" />
<ImageView
android:id="#+id/btPlayMusic"
android:layout_width="80dp"
android:layout_height="80dp"
android:alpha="0.9"
android:background="#drawable/play"
android:theme="#style/Button.White"
app:layout_constraintEnd_toStartOf="#+id/text_time"
app:layout_constraintStart_toEndOf="#+id/playerPositionMusic"
app:layout_constraintTop_toBottomOf="#+id/seekBarMusic1"
app:tint="#color/remain_black" />
<ImageView
android:visibility="gone"
android:id="#+id/btPauseMusic"
android:layout_width="80dp"
android:layout_height="80dp"
android:alpha="0.9"
android:background="#drawable/pause"
android:theme="#style/Button.White"
app:layout_constraintEnd_toStartOf="#+id/text_time"
app:layout_constraintStart_toEndOf="#+id/playerPositionMusic"
app:layout_constraintTop_toBottomOf="#+id/seekBarMusic1"
app:tint="#color/remain_black" />
The code I used before:
public class m1 extends AppCompatActivity {
ImageView btPlay, btPause;
TextView playerPosition, playerDuration;
CircularSeekBar seekBar;
MediaPlayer mediaPlayer;
Handler handler = new Handler();
Runnable runnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_m1);
findViewById(R.id.backm1).setOnClickListener(v -> onBackPressed());
playerPosition = findViewById(R.id.playerPosition);
playerDuration = findViewById(R.id.playerDuration);
replay = findViewById(R.id.replay);
forward = findViewById(R.id.forward);
seekBar = findViewById(R.id.seekBar);
btPause = findViewById(R.id.btPause);
btPlay = findViewById(R.id.btPlay);
mediaPlayer = MediaPlayer.create(this,R.raw.ding_dong);
runnable = new Runnable() {
#Override
public void run() {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
handler.postDelayed(this,500);
}
};
int duration = mediaPlayer.getDuration();
String sDuration = convertFormat(duration);
playerDuration.setText(sDuration);
btPlay.setOnClickListener(v -> {
mediaPlayer.start();
btPlay.setVisibility(View.GONE);
btPause.setVisibility(View.VISIBLE);
seekBar.setMax(mediaPlayer.getDuration());
handler.postDelayed(runnable, 0)
});
btPause.setOnClickListener(v -> {
mediaPlayer.stop();
btPause.setVisibility(View.GONE);
btPlay.setVisibility(View.VISIBLE);
handler.removeCallbacks(runnable);
});
seekBar.setOnSeekBarChangeListener(new CircularSeekBar.OnCircularSeekBarChangeListener() {
#Override
public void onProgressChanged(CircularSeekBar circularSeekBar, float v, boolean b) {
if (b) {
mediaPlayer.seekTo((int) v);
}
playerPosition.setText(convertFormat(mediaPlayer.getCurrentPosition()));
}
#Override
public void onStopTrackingTouch(CircularSeekBar circularSeekBar) {
}
#Override
public void onStartTrackingTouch(CircularSeekBar circularSeekBar) {
}
});
mediaPlayer.setOnCompletionListener(mp -> {
btPause.setVisibility((View.GONE));
btPlay.setVisibility(View.VISIBLE);
mediaPlayer.seekTo(0);
});
}
}
#SuppressLint("DefaultLocale")
private String convertFormat(int duration) {
return String.format("%02d:%02d"
,TimeUnit.MILLISECONDS.toMinutes(duration)
,TimeUnit.MILLISECONDS.toSeconds(duration) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration)));
}
#Override
public void onPause()
{
if(mediaPlayer != null && mediaPlayer.isPlaying())
{
mediaPlayer.stop();
}
super.onPause();
}
}
The code I am using now:
btPause = findViewById(R.id.btPauseMusic);
btPlay = findViewById(R.id.btPlayMusic);
btPlay.setOnClickListener(v -> {
startService(new Intent(this, BackgroundMusicService.class));
btPlay.setVisibility(View.GONE);
btPause.setVisibility(View.VISIBLE);
});
btPause.setOnClickListener(v -> {
stopService(new Intent(this, BackgroundMusicService.class));
btPause.setVisibility(View.GONE);
btPlay.setVisibility(View.VISIBLE);
});
}
And the service class:
public class BackgroundMusicService extends Service {
private MediaPlayer mediaPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mediaPlayer = MediaPlayer.create(this, R.raw.ding_dong);
mediaPlayer.start();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
}
}
You are using different MediaPlayer in the Activity from the one in the backgroundService
you don't need to initialize another mediaPlayer in the activity you have to control the one in the backgroundService with Broadcast receivers like this for example to pause a the mediaPlayer in the backgroundService you do something like this
private BroadcastReceiver pausePlayingAudio = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
pause();
updateMetaData();
buildNotification(PlaybackStatus.PAUSED);
playbackStatus = PlaybackStatus.PAUSED ;
}
};
private void register_pausePlayingAudio(){
IntentFilter intentFilter = new IntentFilter(SongAdapter.ACTION_PAUSE) ;
registerReceiver(pausePlayingAudio , intentFilter) ;
}
and you call register_pausePlayingAudio() in onCreate() of the backGroundService
now say when a user clicks on a button in the activity and you want to pause you use something like this
sendBroadcast(new Intent(SongAdapter.ACTION_PAUSE));
I have and old project not finished doesn't have a seekBar but the seekBar implementation will be similar just instead of pause() you call seekTo() so you can check it
the repo
This article Creating Media player service shows step by step on how you can implement a service to create a Mediaplayer application to run in the background.

Using the camera in android

I am trying to build an Android app that simply uses the camera to take a picture without launching the default camera app. In other words, I want to make a custom camera app. I can do this using the Camera hardware object class, however this is deprecated and I want to use some of the new features of camerax and not have to worry about the code not working after some time. I have also read the camera API documentation, however it is still unclear how to use the camera. Are there any very simple step by step tutorials or guides that might help me?
Thanks,
You can check my example about how to use AndroidX libraries and TextureView for camera customization.
https://github.com/icerrate/Custom-Camera-App
First at all, define your layout. This is my activity_main.xml file:
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextureView
android:id="#+id/view_finder"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/take_photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_margin="#dimen/horizontal_margin"
app:layout_constraintStart_toStartOf="parent"
android:src="#drawable/ic_camera"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Remember that TextureView will receive the camera preview and the Floating Action Button works as a "Take Photo" button.
Then add your MainActivity.java file:
public class MainActivity extends AppCompatActivity implements LifecycleOwner {
private static final int RC_PERMISSIONS = 100;
private TextureView viewFinder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
viewFinder = findViewById(R.id.view_finder);
FloatingActionButton takePhotoFab = findViewById(R.id.take_photo);
//Check permissions
if (allPermissionGranted()) {
viewFinder.post(new Runnable() {
#Override
public void run() {
startCamera();
}
});
} else {
ActivityCompat.requestPermissions(this,
new String[] {Manifest.permission.CAMERA}, RC_PERMISSIONS);
}
takePhotoFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takePhoto();
}
});
}
private void startCamera() {
Point screenSize = getScreenSize();
int width = screenSize.x;
int height = screenSize.y;
//Get real aspect ratio
DisplayMetrics displayMetrics = new DisplayMetrics();
Display display = getWindowManager().getDefaultDisplay();
display.getRealMetrics(displayMetrics);
Rational rational = new Rational(displayMetrics.widthPixels, displayMetrics.heightPixels);
//Build the camera preview
PreviewConfig build = new PreviewConfig.Builder()
.setTargetAspectRatio(rational)
.setTargetResolution(new Size(width,height))
.build();
Preview preview = new Preview(build);
preview.setOnPreviewOutputUpdateListener(new Preview.OnPreviewOutputUpdateListener() {
#Override
public void onUpdated(Preview.PreviewOutput output) {
ViewGroup group = (ViewGroup) viewFinder.getParent();
group.removeView(viewFinder);
group.addView(viewFinder, 0);
viewFinder.setSurfaceTexture(output.getSurfaceTexture());
}
});
CameraX.bindToLifecycle(this, preview);
}
private void takePhoto() {
Toast.makeText(this, "Shot!",
Toast.LENGTH_SHORT).show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == RC_PERMISSIONS) {
if (allPermissionGranted()) {
viewFinder.post(new Runnable() {
#Override
public void run() {
startCamera();
}
});
} else {
Toast.makeText(this, "Permission not granted",
Toast.LENGTH_SHORT).show();
finish();
}
}
}
private boolean allPermissionGranted() {
return ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
}
private Point getScreenSize() {
Display display = getWindowManager(). getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return size;
}
}
In this class, you would be able to send the camera preview to the TextureView, with help of PreviewConfig.Builder() and binding it to the Activity lifeCycle using CameraX.bindToLifeCycle()
Also, don't forget to add Camera permission to the manifest and consider runtime permissions.
Screenshot:
Custom Camera preview
Hope this help you!

Android. Problems when applying custom animation on multiple views

I have written my own shake animation to shake the EditTexts. When I tap "SHAKE USER", the first EditText shakes. When I tap "SHAKE PASS", the two EditTexts shake together, which should not happen. Screenshot is attached.Screenshot
Here is the animation file
shake.xml
<?xml version="1.0" encoding="utf-8"?>
<set
xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="#android:anim/linear_interpolator"
android:fillAfter="true">
<translate
android:fromXDelta="0%p"
android:toXDelta="2%"
android:repeatCount="5"
android:repeatMode="reverse"
android:interpolator="#android:anim/linear_interpolator"
android:duration="50" />
</set>
Here is the Java code snippet
Animation shake = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.shake);
findViewById(R.id.b1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
shakeView(etUser);
}
});
findViewById(R.id.b2).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
shakeView(etPass);
}
});
private void shakeView(final View view) {
new Thread(new Runnable() {
#Override
public void run() {
view.post(new Runnable() {
#Override
public void run() {
view.startAnimation(shake);
}
});
}
}).start();
}
Thanks!
Seems that I have found the solution myself. I called view.clearAnimation() after the animation finishes, and everything is working fine

VideoView Streaming: Audio works but video is black

I have a very strange issue. I am using a steam video and I play it on my app but the issue is that Audio works but video is not working. It shows a black screen (See image for reference.) I have no idea what the issue is. Audio works fine but video shows black screen.
Any ideas of what the issue can be?
Here is my code for reference:
public class Video_Low_Mission extends Activity {
// Put in your Video URL here
private String VideoURL = "rtsp://184.72.239.149/vod/mp4:BigBuckBunny_175k.mov";
// Declare some variables
private ProgressDialog pDialog;
VideoView videoview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the layout from video_main.xml
setContentView(R.layout.activity_video__low__mission);
// Find your VideoView in your video_main.xml layout
videoview = (VideoView) findViewById(R.id.VideoView);
// Execute StreamVideo AsyncTask
new StreamVideo().execute();
}
// StreamVideo AsyncTask
private class StreamVideo extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressbar
pDialog = new ProgressDialog(Video_Low_Mission.this);
// Set progressbar title
pDialog.setTitle("Mission TV (Low Quality)");
// Set progressbar message
pDialog.setMessage("Buffering...");
pDialog.setIndeterminate(false);
// Show progressbar
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(Void args) {
try {
// Start the MediaController
MediaController mediacontroller = new MediaController(
Video_Low_Mission.this);
mediacontroller.setAnchorView(videoview);
// Get the URL from String VideoURL
Uri video = Uri.parse(VideoURL);
videoview.setMediaController(mediacontroller);
videoview.setVideoURI(video);
videoview.requestFocus();
videoview.setOnPreparedListener(new OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
pDialog.dismiss();
videoview.start();
}
});
} catch (Exception e) {
pDialog.dismiss();
// Error Here
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
}
// Not using options menu for this tutorial
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.video__low__mission, menu);
return true;
}
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:layout_width="fill_parent"
android:layout_height="fill_parent" >
<VideoView
android:id="#+id/VideoView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</RelativeLayout>
Thanks :)
Playing of mov files is not supported on the android. mov is an apple format, and there is not a default video codec in android to play them. Reference
You can try vitamio framework, it supports .mov format. Check also this decription.
I solved this issue with the following code, I hope it works for you.
videoView.setBackgroundColor(Color.TRANSPARENT);

when video finished go back to activity

I have some videos using videoView. everything is running well, but when the video is finished nothing happens, the phone stay on dark screen waiting to pres play again or the blink back on the phone.
I want that when videos is finished, go back to the activity before. this is my code.
public class chapterone extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.videoplayer);
VideoView videoView =
(VideoView)this.findViewById(R.id.videoView);
MediaController mc = new MediaController(this);
videoView.setMediaController(mc);
videoView.setVideoURI(Uri.parse(
"http://video.com/episode/" +
"cotton1.mp4"));
/* videoView.setVideoPath(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES) +
"/movie.mp4");
*/
videoView.requestFocus();
videoView.start();
}
}
the URL is only an example.
videoView.setOnCompletionListener(completionListener);
OnCompletionListener completionListener=new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.stop();
chapterone.this.finish();
}
};
i hope can help i found this, but i am not sure if is correct uset it
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
#Override
public void onCompletion(MediaPlayer mp){
// invoke your activity here
Intent i = new Intent(chapterone.this, videoserie.class);
startActivity(i);
}
});

Categories