在瀏覽器中實現實現視頻播放器

為了使用Flutter在iOS或Android上播放視頻,大多數人會轉向video_player軟件包。

不幸的是,Web平臺不支持該軟件包。我們將探索一種使我們能夠通過3個簡單步驟播放視頻的解決方案:

1.我們需要編輯Web文件夾中的默認index.html模板文件。有了這些修改,我們加載afterglowplayer,並建立一個觸發器,在一個 HTML元素,和視頻,將作為我們所要播放視頻的佔位符HTML元素。

這就是我們的index.html的樣子:





<title>Web Video Player/<title>




<video>
/<video>


2.然後,我們編寫一個名為playVideo的Dart函數,該函數將使用Universal_html包與index.html頁面進行交互,並傳遞我們要播放的視頻URL:

import 'package:flutter/foundation.dart';
import 'package:universal_html/html.dart' as html;void **playVideo**(String **atUrl**) {
if(**kIsWeb**) {
final v = html.window.document.getElementById('**videoPlayer**');
if(v != null) {
v.**setInnerHtml**(
'<source>',
validator: html.NodeValidatorBuilder()
..allowElement('source', attributes: ['src', 'type']));
final a = html.window.document.getElementById( '**triggerVideoPlayer**' );
if(a != null) {
a.dispatchEvent(html.MouseEvent('click'));
}
}
} else {
// we're not on the web platform
// and should use the [video_player](https://pub.dev/packages/video_player) package
}
}

/<source>

該代碼引用了videoPlayer元素,如果存在,則設置其內部HTML以容納我們使用atUrl參數傳遞的視頻URL 。然後,我們獲取有關triggerVideoPlayer元素的參考,並觸發鼠標單擊。

3.視頻將作為整個Flutter應用程序頂部的疊加播放。播放器反應靈敏,並提供播放暫停音量滾動

全屏控制,並顯示播放信息。

playVideo('http://distribution.bbb3d.renderfarming.net/video/mp4/bbb_sunflower_1080p_30fps_normal.mp4');
Flutter - 在瀏覽器中實現實現視頻播放器



如果您需要播放縱向視頻(或以縱向模式播放視頻),則可以在步驟1 中將寬度高度交換,或者通過修改playVideo功能來動態地實現。

Afterglow player可以進一步自定義。僅通過將視頻ID作為參數發送到步驟2的位修改方法,它也可以播放YouTubeVimeo視頻。

import 'package:flutter/foundation.dart';
import 'package:universal_html/html.dart' as html;void **playHostedVideo**(String **withId,** [bool **isVimeo**=false]) {
if(**kIsWeb**) {
final v = html.window.document.getElementById('**videoPlayer**');
if(v != null) {
if(isVimeo) {
v.setAttribute("data-vimeo-id", withId);
} else {
v.setAttribute("data-youtube-id", withId);
}
final a = html.window.document.getElementById( '**triggerVideoPlayer**' );
if(a != null) {
a.dispatchEvent(html.MouseEvent('click'));
}
}
} else {
// we're not on the web platform

// and should use the [video_player](https://pub.dev/packages/video_player) package
}
}

第3步變為:

// for playing YouTube video
playHostedVideo('aqz-KE-bpKQ');
// or for playing Vimeo video
playHostedVideo('1084537', true);

作為底注,可以像這樣使用任何HTML / JS視頻播放器。在最近的項目中使用了Afterglow之後,我選擇了Afterglow,我喜歡它的簡單性以及它的輕巧性。

翻譯自:https://medium.com/flutter-community/flutter-video-player-3a2f4f8562a3


分享到:


相關文章: