Flutter无法显示视频

2024-01-18

import 'package:video_player/video_player.dart';
import 'package:flutter/material.dart';

void main() => runApp(VideoApp());
class VideoApp extends StatefulWidget {
@override
_VideoAppState createState() => _VideoAppState();
}
class _VideoAppState extends State<VideoApp> {
VideoPlayerController _controller;
@override
void initState() {
super.initState();
_controller = VideoPlayerController.network(
    'https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4')
  ..initialize().then((_) {
    // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
    setState(() {});
  });
  }
@override
Widget build(BuildContext context) {
return MaterialApp(
  title: 'Video Demo',
  home: Scaffold(
    body: Center(
      child: _controller.value.isInitialized
          ? AspectRatio(
              aspectRatio: _controller.value.aspectRatio,
              child: VideoPlayer(_controller),
            )
          : Container(),
    ),
    floatingActionButton: FloatingActionButton(
      onPressed: () {
        setState(() {
          _controller.value.isPlaying
              ? _controller.pause()
              : _controller.play();
        });
      },
      child: Icon(
        _controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
      ),
    ),
  ),
);
 }
 @override
 void dispose() {
super.dispose();
_controller.dispose();
}
}

尽管我尝试添加依赖项并将视频链接更改为 YouTube 链接,但它仍然相同并且不显示视频。我可以知道如何解决这个问题吗?有一些错误,我列出如下:

  1. 未为类型“_VideoAppState”定义方法“VideoPlayer”
  2. 未定义名称“VideoPlayerController”。
  3. 未定义的类“VideoPlayerController”。
  4. URI 目标不存在:'package:video_player/video_player.dart'

下面的 Pubspec.yaml

    name: icseat
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  
  dio: ^4.0.0
  file_picker: ^4.0.0
  video_player:
  advance_pdf_viewer: ^2.0.0
  flutter:
    sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  http: ^0.13.0

dev_dependencies:
  flutter_test:
    sdk: flutter

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  assets:
    - images/logoicseat.png
    - images/person.png
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

@Tommie C.以下是我在运行代码时遇到的错误:

Launching lib\View\Video.dart on sdk gphone x86 arm in debug mode...
Running Gradle task 'assembleDebug'...
√  Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...
Debug service listening on ws://127.0.0.1:57805/tl8ztZ-XWag=/ws
Syncing files to device sdk gphone x86 arm...
W/e.icseattestin( 4832): Accessing hidden method Landroid/media/AudioTrack;->getLatency()I (greylist, reflection, allowed)
I/ExoPlayerImpl( 4832): Init bda4bd9 [ExoPlayerLib/2.14.1] [generic_x86_arm, sdk_gphone_x86_arm, Google, 30]
I/Choreographer( 4832): Skipped 54 frames!  The application may be doing too much work on its main thread.
I/OpenGLRenderer( 4832): Davey! duration=921ms; Flags=0, IntendedVsync=313961916316, Vsync=314861916280, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=314868026700, AnimationStart=314868094000, PerformTraversalsStart=314871530500, DrawStart=314873232800, SyncQueued=314874438400, SyncStart=314875924800, IssueDrawCommandsStart=314875998400, SwapBuffers=314879263000, FrameCompleted=314885090400, DequeueBufferDuration=1230100, QueueBufferDuration=3509200, GpuCompleted=0, 
I/TetheringManager( 4832): registerTetheringEventCallback:com.example.icseattesting
I/VideoCapabilities( 4832): Unsupported profile 4 for video/mp4v-es
I/OMXClient( 4832): IOmx service obtained
D/SurfaceUtils( 4832): connecting to surface 0xe4d1c578, reason connectToSurface
I/MediaCodec( 4832): [OMX.android.goldfish.h264.decoder] setting surface generation to 4947969
D/SurfaceUtils( 4832): disconnecting from surface 0xe4d1c578, reason connectToSurface(reconnect)
D/SurfaceUtils( 4832): connecting to surface 0xe4d1c578, reason connectToSurface(reconnect)
E/ACodec  ( 4832): [OMX.android.goldfish.h264.decoder] setPortMode on output to DynamicANWBuffer failed w/ err -1010
I/ACodec  ( 4832): codec does not support config priority (err -1010)
D/SurfaceUtils( 4832): disconnecting from surface 0xe4d1c578, reason setNativeWindowSizeFormatAndUsage
D/SurfaceUtils( 4832): connecting to surface 0xe4d1c578, reason setNativeWindowSizeFormatAndUsage
D/SurfaceUtils( 4832): set up nativeWindow 0xe4d1c578 for 1280x720, color 0x13, rotation 0, usage 0x1002900
W/Gralloc4( 4832): allocator 3.x is not supported
Lost connection to device.

Update:

注意:在下面的示例中,您可以注释掉尝试加载 srt 字幕文件的行(closedCaptionFile: _loadCaptions,).

将 pubspec.yaml 中的以下内容更改为video_player: ^2.1.15

注意 - 另外,您是否尝试在 iOS 或 Android 中运行此程序?确保你打开 Runner.xcworkspace 文件并执行标准 Xcode 例程。制作 确保 Runner 项目和 pods 项目可见。尝试 跑步flutter build ios从航站楼。

然后重新运行flutter pub get或单击 UI 中的获取依赖项。我还会制作一个演示项目(存根 -flutter create --org com.yoursite stub01)并添加提供的示例以查看在线示例是否正常工作。

Original:

这是来自的完整示例插件网站 https://pub.dev/packages/video_player/example对于视频播放器。您可以将其粘贴到您的环境中以确保一切正常。您还应该确保您按照设置步骤授予您的 iOS/Android 应用程序访问互联网的权限(请参阅安装注意事项 https://pub.dev/packages/video_player在网站的自述文件部分)。我还要确保跑flutter upgrade在您的终端上。

// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// ignore_for_file: public_member_api_docs

/// An example of using the plugin, controlling lifecycle and playback of the
/// video.

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

void main() {
  runApp(
    MaterialApp(
      home: _App(),
    ),
  );
}

class _App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 3,
      child: Scaffold(
        key: const ValueKey<String>('home_page'),
        appBar: AppBar(
          title: const Text('Video player example'),
          actions: <Widget>[
            IconButton(
              key: const ValueKey<String>('push_tab'),
              icon: const Icon(Icons.navigation),
              onPressed: () {
                Navigator.push<_PlayerVideoAndPopPage>(
                  context,
                  MaterialPageRoute<_PlayerVideoAndPopPage>(
                    builder: (BuildContext context) => _PlayerVideoAndPopPage(),
                  ),
                );
              },
            )
          ],
          bottom: const TabBar(
            isScrollable: true,
            tabs: <Widget>[
              Tab(
                icon: Icon(Icons.cloud),
                text: "Remote",
              ),
              Tab(icon: Icon(Icons.insert_drive_file), text: "Asset"),
              Tab(icon: Icon(Icons.list), text: "List example"),
            ],
          ),
        ),
        body: TabBarView(
          children: <Widget>[
            _BumbleBeeRemoteVideo(),
            _ButterFlyAssetVideo(),
            _ButterFlyAssetVideoInList(),
          ],
        ),
      ),
    );
  }
}

class _ButterFlyAssetVideoInList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListView(
      children: <Widget>[
        _ExampleCard(title: "Item a"),
        _ExampleCard(title: "Item b"),
        _ExampleCard(title: "Item c"),
        _ExampleCard(title: "Item d"),
        _ExampleCard(title: "Item e"),
        _ExampleCard(title: "Item f"),
        _ExampleCard(title: "Item g"),
        Card(
            child: Column(children: <Widget>[
          Column(
            children: <Widget>[
              const ListTile(
                leading: Icon(Icons.cake),
                title: Text("Video video"),
              ),
              Stack(
                  alignment: FractionalOffset.bottomRight +
                      const FractionalOffset(-0.1, -0.1),
                  children: <Widget>[
                    _ButterFlyAssetVideo(),
                    Image.asset('assets/flutter-mark-square-64.png'),
                  ]),
            ],
          ),
        ])),
        _ExampleCard(title: "Item h"),
        _ExampleCard(title: "Item i"),
        _ExampleCard(title: "Item j"),
        _ExampleCard(title: "Item k"),
        _ExampleCard(title: "Item l"),
      ],
    );
  }
}

/// A filler card to show the video in a list of scrolling contents.
class _ExampleCard extends StatelessWidget {
  const _ExampleCard({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          ListTile(
            leading: const Icon(Icons.airline_seat_flat_angled),
            title: Text(title),
          ),
          ButtonBar(
            children: <Widget>[
              TextButton(
                child: const Text('BUY TICKETS'),
                onPressed: () {
                  /* ... */
                },
              ),
              TextButton(
                child: const Text('SELL TICKETS'),
                onPressed: () {
                  /* ... */
                },
              ),
            ],
          ),
        ],
      ),
    );
  }
}

class _ButterFlyAssetVideo extends StatefulWidget {
  @override
  _ButterFlyAssetVideoState createState() => _ButterFlyAssetVideoState();
}

class _ButterFlyAssetVideoState extends State<_ButterFlyAssetVideo> {
  late VideoPlayerController _controller;

  @override
  void initState() {
    super.initState();
    _controller = VideoPlayerController.asset('assets/Butterfly-209.mp4');

    _controller.addListener(() {
      setState(() {});
    });
    _controller.setLooping(true);
    _controller.initialize().then((_) => setState(() {}));
    _controller.play();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: <Widget>[
          Container(
            padding: const EdgeInsets.only(top: 20.0),
          ),
          const Text('With assets mp4'),
          Container(
            padding: const EdgeInsets.all(20),
            child: AspectRatio(
              aspectRatio: _controller.value.aspectRatio,
              child: Stack(
                alignment: Alignment.bottomCenter,
                children: <Widget>[
                  VideoPlayer(_controller),
                  _ControlsOverlay(controller: _controller),
                  VideoProgressIndicator(_controller, allowScrubbing: true),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _BumbleBeeRemoteVideo extends StatefulWidget {
  @override
  _BumbleBeeRemoteVideoState createState() => _BumbleBeeRemoteVideoState();
}

class _BumbleBeeRemoteVideoState extends State<_BumbleBeeRemoteVideo> {
  late VideoPlayerController _controller;

  Future<ClosedCaptionFile> _loadCaptions() async {
    final String fileContents = await DefaultAssetBundle.of(context)
        .loadString('assets/bumble_bee_captions.srt');
    return SubRipCaptionFile(fileContents);
  }

  @override
  void initState() {
    super.initState();
    _controller = VideoPlayerController.network(
      'https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4',
     // closedCaptionFile: _loadCaptions(),
      videoPlayerOptions: VideoPlayerOptions(mixWithOthers: true),
    );

    _controller.addListener(() {
      setState(() {});
    });
    _controller.setLooping(true);
    _controller.initialize();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: <Widget>[
          Container(padding: const EdgeInsets.only(top: 20.0)),
          const Text('With remote mp4'),
          Container(
            padding: const EdgeInsets.all(20),
            child: AspectRatio(
              aspectRatio: _controller.value.aspectRatio,
              child: Stack(
                alignment: Alignment.bottomCenter,
                children: <Widget>[
                  VideoPlayer(_controller),
                  ClosedCaption(text: _controller.value.caption.text),
                  _ControlsOverlay(controller: _controller),
                  VideoProgressIndicator(_controller, allowScrubbing: true),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _ControlsOverlay extends StatelessWidget {
  const _ControlsOverlay({Key? key, required this.controller})
      : super(key: key);

  static const _examplePlaybackRates = [
    0.25,
    0.5,
    1.0,
    1.5,
    2.0,
    3.0,
    5.0,
    10.0,
  ];

  final VideoPlayerController controller;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        AnimatedSwitcher(
          duration: Duration(milliseconds: 50),
          reverseDuration: Duration(milliseconds: 200),
          child: controller.value.isPlaying
              ? SizedBox.shrink()
              : Container(
                  color: Colors.black26,
                  child: Center(
                    child: Icon(
                      Icons.play_arrow,
                      color: Colors.white,
                      size: 100.0,
                    ),
                  ),
                ),
        ),
        GestureDetector(
          onTap: () {
            controller.value.isPlaying ? controller.pause() : controller.play();
          },
        ),
        Align(
          alignment: Alignment.topRight,
          child: PopupMenuButton<double>(
            initialValue: controller.value.playbackSpeed,
            tooltip: 'Playback speed',
            onSelected: (speed) {
              controller.setPlaybackSpeed(speed);
            },
            itemBuilder: (context) {
              return [
                for (final speed in _examplePlaybackRates)
                  PopupMenuItem(
                    value: speed,
                    child: Text('${speed}x'),
                  )
              ];
            },
            child: Padding(
              padding: const EdgeInsets.symmetric(
                // Using less vertical padding as the text is also longer
                // horizontally, so it feels like it would need more spacing
                // horizontally (matching the aspect ratio of the video).
                vertical: 12,
                horizontal: 16,
              ),
              child: Text('${controller.value.playbackSpeed}x'),
            ),
          ),
        ),
      ],
    );
  }
}

class _PlayerVideoAndPopPage extends StatefulWidget {
  @override
  _PlayerVideoAndPopPageState createState() => _PlayerVideoAndPopPageState();
}

class _PlayerVideoAndPopPageState extends State<_PlayerVideoAndPopPage> {
  late VideoPlayerController _videoPlayerController;
  bool startedPlaying = false;

  @override
  void initState() {
    super.initState();

    _videoPlayerController =
        VideoPlayerController.asset('assets/Butterfly-209.mp4');
    _videoPlayerController.addListener(() {
      if (startedPlaying && !_videoPlayerController.value.isPlaying) {
        Navigator.pop(context);
      }
    });
  }

  @override
  void dispose() {
    _videoPlayerController.dispose();
    super.dispose();
  }

  Future<bool> started() async {
    await _videoPlayerController.initialize();
    await _videoPlayerController.play();
    startedPlaying = true;
    return true;
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      elevation: 0,
      child: Center(
        child: FutureBuilder<bool>(
          future: started(),
          builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
            if (snapshot.data == true) {
              return AspectRatio(
                aspectRatio: _videoPlayerController.value.aspectRatio,
                child: VideoPlayer(_videoPlayerController),
              );
            } else {
              return const Text('waiting for video to load');
            }
          },
        ),
      ),
    );
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Flutter无法显示视频 的相关文章

随机推荐

  • MVC 与区域 - Html.ActionLink 返回错误的 URL/路线?

    我正在使用 MVC3 并在我的应用程序中有区域 一般来说 一切正常 我可以导航到我的区域 例如 Admin Area Controller Department 如下所示 然而 我注意到 如果我没有在 ActionLink 中指定区域 例如
  • 在循环内增加时间 15 分钟[重复]

    这个问题在这里已经有答案了 我想创建一个下拉菜单 它将当前时间作为开始时间 直到 24 小时为止 就像直到 24 小时之前 所以在这之间它将显示每 15 分钟增量的时间 问题是 当我尝试运行循环时 起始时间还可以 但在下一个循环中 时间会跳
  • 使用apache服务器时覆盖python3默认编码器

    我正在运行一个 apache 服务器 它服务于一个名为巧妙 http inginious readthedocs io Getting UnicodeDecodeError ascii 读取带有希伯来字符的文件时 我读到您可以使用环境变量更
  • 如何在Client中获取socket.io客户端的session id

    我想在我的 socket io 客户端中获取客户端的会话 ID 这是我的 socket io 客户端 var socket new io Socket config host port config port rememberTranspo
  • Google App Engine app.yaml 中的反向skip_files

    我目前有以下内容skip files在我的 app yaml 中 skip files json yaml Gruntfile js bower components node modules src tests tmp 这实在是太臃肿了
  • Ruby 中的“<<-”是什么意思?

    例如 code lt lt EOH bundle install bundle exec unicorn c etc unicorn cfg D EOH 这段代码有什么作用 什么是 lt lt called 它被称为定界符 定义多行字符串的
  • 在 CATextLayer 中显示属性字符串

    我有一个简单的示例应用程序 我在其中创建了一个CATextLayer并设置其string财产给NSAttributedString 然后我将该 CATextLayer 添加到视图中 import
  • 给定一个整数数组,找到第一个唯一的整数

    给定一个整数数组 找到第一个唯一的整数 我的解决方案 使用std map 将整数 数字作为键 其索引作为值 一一放入其中 O n 2 lgn 如果有重复 则从地图中删除该条目 O lg n 将所有数字放入映射后 迭代映射并找到索引最小 O
  • 如何覆盖视频的 i 帧?

    我想销毁视频的所有 i 帧 这样做我想检查仅加密视频的 i 帧是否足以使其无法观看 我怎样才能做到这一点 仅删除它们并重新压缩视频与真正覆盖流中的 i 帧而不重新计算 b 帧等不同 使用 libavformat 来自 ffmpeg 的库 您
  • 如何在多线程环境中使用旧的单线程 C++ 库

    我有一个旧的 C 库 它是为在单线程环境中使用而设计的 该库公开了用于初始化的接口 这改变了库的内部数据结构 以及仅读取数据和进行计算的用法 我的目标是在 Windows 多线程应用程序中使用这个库 不同的线程调用使用不同数据初始化的 dl
  • 如何确保python脚本使用虚拟环境?

    我创建了虚拟环境并激活它 已安装软件包但无法从虚拟环境导入它们 pip freeze 但尝试导入模块时出错 Traceback most recent call last File z Documents Python Projects P
  • 比较 std::wstring 和 std::string

    我怎样才能比较wstring 例如L Hello to a string 如果我需要相同的类型 如何将它们转换为相同的类型 既然你问了 这是我从字符串到宽字符串的标准转换函数 使用 C 实现std string and std wstrin
  • 通过jenkins上传.ipa到testflight

    我正在使用詹金斯进行自动构建和自动部署 到目前为止 我成功地实现了构建生成 即 ipa 文件 我还实现了diawi链接生成 现在我想通过 jenkins 将 ipa 上传到 testflight 现在我正在使用这个脚本进行上传 ipa di
  • IE7 无法识别文本输入只读属性?

    我通过 javascript 设置 readonly readonly 换句话说 true document getElementById my id setAttribute readonly readonly 这在 FF Safari
  • 插入到数组中不存在的索引处

    我正在尝试使用从数据库中提取的数据来格式化 JavaScript 中的数组 以便行的 ID 是数组的索引 因此数据 ID Data 1 hi 2 more data 4 junk data 8 hello world 12 h3ll0 看起
  • 使用指针的字符串长度

    我正在寻找一些代码技巧 我发现一个我了解了基础知识但我不明白它为什么存在的原因 它与 while 循环中的字符串指针有关 通常我不处理字符串 因为我主要在嵌入式系统 小工具上工作 我需要理解为什么字符串指针在不增加时会结束 因此 在这段代码
  • 在 Python 中使用 OpenCV VideoCapture 获取当前帧

    我正在使用 cv2 VideoCapture 在 python 脚本中读取 RTSP 视频链接的帧 read 函数位于每秒运行一次的 while 循环中 但是 我没有从流中获取最新的帧 我使用较旧的帧 这样我的延迟就增加了 无论如何 我是否
  • 创建一个真正的无头 QApplication 实例

    我有一个 Qt 5 8 通过 PyQt5 应用程序 其许多测试需要实时QApplication实例以测试 gui 小部件交互 然而 在我的新 Mac OS X 10 11 6 机器上 运行这些测试时 窗口不断被创建和销毁 导致整个系统的 U
  • 使用 Google 新闻 RSS URL 时如何指定检索本地新闻?

    我正在尝试构建一个使用 Google News RSS 的 RSS 解析器 我只需定位以下 URL 即可从新闻 URL 检索新闻文章 https news google com news section output rss 但是 在谷歌新
  • Flutter无法显示视频

    import package video player video player dart import package flutter material dart void main gt runApp VideoApp class Vi