我需要在本地的文件中选择一段视频(IOS则是在相册中选择),然后首先预览,确定无误后上传到服务器。
首先,我使用了 image_picker,从本地选择了文件,按钮代码如下:
onPressed: () async {
final ImagePicker _picker = ImagePicker();
final XFile? pickedOne = await _picker.pickVideo(
maxDuration: const Duration(seconds: 30),
source: ImageSource.gallery);
setState(() {
// 这里我是用于传递参数
video = pickedOne;
});
},
然后我点击视频,打开预览页,跳转携带参数,我用的是 video_player 代码如下:
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PreviewVideoDialog(
previewUrl: video!.path)),
);
最后,我把 PreviewVideoDialog 的代码也放出来:
class PreviewVideoDialog extends StatefulWidget {
final String previewUrl;
const PreviewVideoDialog({Key? key, required this.previewUrl})
: super(key: key);
State<PreviewVideoDialog> createState() => _PreviewVideoDialogState();
}
class _PreviewVideoDialogState extends State<PreviewVideoDialog> {
late VideoPlayerController _controller;
void initState() {
super.initState();
_controller = VideoPlayerController.asset(
// 播放传递过来的视频 url
widget.previewUrl,
)..initialize().then((_) {
// Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
setState(() {});
});
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Video Demo'),
),
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,
),
),
);
}
void dispose() {
super.dispose();
_controller.dispose();
}
}
然后就直接崩溃了。我打印过传递过来的url,是 /Users/Lucky/Library/Developer/CoreSimulator/Devices/51B8B0B2-1E50-43BA-B56F-EC39F1787B0E/data/Containers/Data/Application/4A271696-B22C-49EC-B242-BB14CAA1CA28/tmp/trim.EEF58395-E172-4470-8AEB-49AF8EED8AA4.MOV
看着没什么问题。
为了定位问题,我把加载本地视频改为了加载网络视频:
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(() {});
});
}
这样也是可以正常播放的。
于是我猜想,是不是跟权限有关系?还望老师解答。提前感谢!😄
补充,崩溃图:
解锁Flutter开发新姿势,,系统掌握Flutter开发核心技术。
了解课程