Flutter VideoPlayer从字节

6bc51xsx  于 2023-05-30  发布在  Flutter
关注(0)|答案(1)|浏览(176)

我正在尝试构建一个应用程序,其中后端生成一个短视频,并在响应中将其作为文件返回。在Flutter前端中,我解析响应对象以获取表示视频的字节。使用这些字节,我想创建一个Video Player
我的问题是如何初始化从响应中收到的字节数组VideoPlayerController
根据文档,VideoPlayerController.file()无法工作,因为这需要dart.io,而该网站上没有。这只剩下networkasset选项。

dgsult0t

dgsult0t1#

下面是一个小的代码实现相同。

class VideoPlayerWidget extends StatefulWidget {
  final Uint8List videoBytes;

  const VideoPlayerWidget({super.key, required this.videoBytes});

  @override
  State<VideoPlayerWidget> createState() => _VideoPlayerWidgetState();
}

class _VideoPlayerWidgetState extends State<VideoPlayerWidget> {
  late VideoPlayerController _controller;
  late html.VideoElement _videoElement;

  @override
  void initState() {
    super.initState();
    _videoElement = html.VideoElement();

    // Register an event listener to track when the video has loaded
    _videoElement.addEventListener('loaded metadata', (_) {
      _initializeVideoPlayer();
    });

    // Convert the byte array to a blob and set it as the video source
    final blob = html.Blob([widget.videoBytes]);
    final url = html.Url.createObjectUrl(blob);
    _videoElement.src = url;
  }

  @override
  void dispose() {
    _controller.dispose();
    _videoElement.pause();
    _videoElement.removeAttribute('src');
    html.Url.revokeObjectUrl(_videoElement.src);
    super.dispose();
  }

  Future<void> _initializeVideoPlayer() async {
    _controller = VideoPlayerController.network(_videoElement.currentSrc!);
    await _controller.initialize();
    await _controller.setLooping(true);
    _controller.play();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    if (_controller.value.isInitialized) {
      return AspectRatio(
        aspectRatio: _controller.value.aspectRatio,
        child: VideoPlayer(_controller),
      );
    } else {
      return Container();
    }
  }
}

您可以将此小部件用作

final Uint8List videobytes; // initalize your video bytes here
VideoPlayerWidget(videoBytes: videoBytes)

相关问题