WebView playback video and pit record

Method 1: AdoptvideoTag built-in capability

Scenario: Play web video directly without other complex interactions (e.g. double speed, gestures, downloads, etc.)

Difficulty: adapt to full screen playback

Solution: Implement WebChromeClient onShowCustomView and onHideCustomView methods, Add the View corresponding to the web video to the DecorView or add it to the Window layer via WindowManager.addView().

Pit: During the test, some videos will be automatically switched back to portrait and non-full screen after being directly switched to landscape full-screen mode. As shown below:

Positioning: It is found that all videos with high ratio and wide width are vertically oriented videos. A look at Google Chrome browsing shows that it will select a full-screen horizontal/vertical mode for the phone based on the aspect ratio of the video. Therefore, it is concluded that the mode cannot be directly switched to landscape full screen mode. It should be judged according to the width and height of the video. If the width of the source video is greater than the height, landscape full screen can be adopted; otherwise, landscape full screen must be vertically displayed.

After receiving the onShowCustomView callback, first render the video in portrait mode, then call the JS method to obtain the width and height of the original video, and decide whether to cut to landscape mode. Here is how js gets the width and height of the video:

function getVideoRect() {
    let tags = document.getElementsByTagName('video');
    if (tags.length > 0) {
        let video = tags[0];
        return {
            'width': video.videoWidth,
            'height': video.videoHeight
        };
    }
    return {};
}
Copy the code

Implementation:

See WebVideoActivity in Web-Video

Method 2: Replace WebView video with native video

Scenario: know the original video address and format; Complex interactions and high performance requirements.

Background: Usually used in hybrid applications, the web page part is displayed with a placeholder map instead of a video tag. When click the play button by calling the native method, the native video to achieve the play function.

Difficulty: determine the layout position and size of native video in WebView.

Because WebView inherits absolute layout, it is also a ViewGroup. So you can call js method to get the position and size (x, Y, width, height) of the video placeholder map in the WebView, and then use these parameters to construct a VideoView to add to the WebView.

/ / in the case of id know placeholder components to obtain high component location and width function getElementRect (id) {let el = window. The document. The getElementById (id); let rect = el.getBoundingClientRect(); return {'top': rect.top, 'left': rect.left, 'width': rect.width, 'height': rect.height}; }Copy the code

implementation

See ExoVideoActivity in Web-video