androidandroid-videoview

Can i loop multiple videos stored on raw folder in videoview?


What im trying to achieve is to play multiple videos stored on raw folder to be played on loop and sequentially one after the other?

I can play only one in loop in videoview but cant access other ones. Thanks in advance. Here is my videoview.

private VideoView myVideo1;
String path = "http://192.168.0.22/output/files/video/";
Uri uri=Uri.parse(path);

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getWindow().setFormat(PixelFormat.TRANSLUCENT);
    setContentView(R.layout.activity_main);
    myVideo1=(VideoView)findViewById(R.id.myvideoview);
    myVideo1.setVideoURI(uri);
    myVideo1.start();
    myVideo1.requestFocus();

    myVideo1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mp.setLooping(true);
        }
    });
}

Solution

  • To play multiple videos located in raw, try the following approach:

    (NOTE: take care of the index and your video files naming. This example assumes your videos are named video1, video2..... videoX)

    private final int COUNT = 3;
    private int index = 1;
    private VideoView myVideo1;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        setContentView(R.layout.activity_main);
        myVideo1 = (VideoView) findViewById(R.id.myvideoview);
        myVideo1.requestFocus();
        myVideo1.setVideoURI(getPath(index));
        index++;
    
        myVideo1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                myVideo1.start();
            }
        });
    
        myVideo1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                    //videos count +1 since we started with 1
                if (index == COUNT + 1) index = 1;
                myVideo1.setVideoURI(getPath(index));
                index++;
            }
        });
    }
    
    private Uri getPath(int id) {
        return Uri.parse("android.resource://" + getPackageName() + "/raw/video" + id);
    }
    

    Getting resources from raw explained: android.resource:// is a constant part of the path, getPackageName() points to your application, /raw/ tells the system where to look for the file, video is the constant naming prefix of your files and the id is a dynamic suffix of your file names.

    VideoView uses the MediaPlayer for playing videos, here's an overview of its states (taken from the official docs) for better understanding:

    enter image description here