I am using the Flutter video_player package here: https://pub.dev/packages/video_player
How do I get the duration of the video? I can see there is a position property, so I would need that to get the current value in time.
But how do I get the total duration of the video? The video is from a URL.
I am making a custom player so I need these two values.
For getting the Total duration you can use the video controller
VideoPlayerController _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.
});
Duration durationOfVideo = _controller.value.duration;
You can also directly store the integer instead of duration as below image
You can create a function to calculate the video Dutarion and format it.
getVideoPosition() {
var duration = Duration(milliseconds: videoController.value.position.inMilliseconds.round());
return [duration.inMinutes, duration.inSeconds].map((seg) => seg.remainder(60).toString().padLeft(2, '0')).join(':');
}
After craeate this function, you just need to call it to show the duration.
Ex.:
Text(getVideoPosition())
Related
Currently i am working on music app and according to my ui i have to manage audio player with carousel slider.The without carousel slider it is working fine but with carousel slider when click on the shuffle or when onPageChanged called, i used the skipToQueueItem for play particular song with audio player, that time suddenly audioHandler.mediaItem listen continuously called and in every 1 second changed song and slider images because of skipToQueueItem line.I used just audio and audio service package.For privacy i am not sharing the code.But for update carousel slider with audio i used below code.
audioHandler.queue.listen((playlist) async {
if (playlist.isEmpty) {
mediaItemsListNotifier.value = [];
} else {
///Update media items notifier list value
mediaItemsListNotifier.value = playlist;
await audioHandler.updateQueue(playlist);
}
});
audioHandler.mediaItem.listen((mediaItem) async {
int index = audioHandler.queue.value.indexOf(mediaItem!);
currentSliderIndex.value = index >= 0 ? index : 0;
///Main issue using this line
await audioHandle.skipToQueueItem(currentSliderIndex.value);
carouselController.jumpToPage(currentSliderIndex.value);
}
I am using video_player for displaying a video. I want to know the if the video reached the last position to display a replay icon and do some logic. How can we approach this in flutter.
_videoController.addListener(() { //custom Listner
setState(() {
if (!_videoController.value.isPlaying &&_videoController.value.initialized &&
(_videoController.value.duration ==_videoController.value.position)) { //checking the duration and position every time
//Video Completed//
// code here to show reply button//
}
});
})
I am using audio_service to play mp3 file. I am following example_playlist as AudioPlayerHander. My code is exactly same as example. But I use dependency injection (get_It) rather than a global variable. And I replace with broadcast media item changes in _init() method to get duration.
Rx.combineLatest5<int?, List<MediaItem>, bool, List<int>?, Duration?,
MediaItem?>(
_player.currentIndexStream,
queue,
_player.shuffleModeEnabledStream,
_player.shuffleIndicesStream,
_player.durationStream, // <- add listening to durationStream here
(index, queue, shuffleModeEnabled, shuffleIndices, duration) {
if (kDebugMode) {
print("${mediaItem.value?.title} - $duration");
}
final queueIndex =
getQueueIndex(index, shuffleModeEnabled, shuffleIndices);
return (queueIndex != null && queueIndex < queue.length)
? queue[queueIndex].copyWith(
duration: duration) // <- sink mediaItem provided with duration
: null;
}).whereType<MediaItem>().distinct().listen(mediaItem.add);
But I did not get the duration correctly.
For playlist 1, it is upload in _init() method and first track's duration is showing correctly but if you click second track, duration is still showing first track's duration.
I have added Load Play List 2 button and load playlist 2. All track's duration is always zero.
Note: audio is playing and start progress from 0 if duration is zero.
If I added playlist 2 in audio_service's example_playlist, it is showing correctly.
So the only different is using global variable and dependency injection (getIt).
I have added sample Github project audio_service_playlist_test
May I know which path is missing?
I have an app where I have an animated check mark made in rive. It is a one shot animation and I want to play it and have it stay in the end of the animation once it's done and then also be able to reverse it when the user clicks on it again. I tried using a SimpleAnimation but I also wasn't able to achieve what I want but it did stay after the animation was done. I don't, however, know how to play an animation and then reverse it or play another animation.
The check mark looks something like this: https://cln.sh/MwLFNs
They are two separate animations but they are copy pasted but in reverse so I can use either one or both.
What I need is to have the animation play and then when the user clicks on the check, I want the animation to change to another one which would then play. How can I achieve this?
Thanks for the help!
you can use State machines, get the state and decide what to do when you want
// Getting state machine
void _onRiveInit(Artboard artboard) async {
final controller =
StateMachineController.fromArtboard(artboard, 'State Machine 1');
if (controller != null) {
artboard.addController(controller);
_lick = controller.findInput<bool>('Lick') as SMITrigger;
}
}
void _onHandlerStateMachine() => _lick?.value = !_lick!.value;
_onRiveInit is a function that is fired when the Rive file is being loading,
after you get the controller to the state machine to modify his state (This is important the name of the State Machine has to be the same of the animation State machine name)
and to modified the value of the trigger your must get the reference on this way
_lick = controller.findInput('Lick') as SMITrigger;
then you can use
void _onHandlerStateMachine() => _lick?.value = !_lick!.value;
to put or remove the animation on any time, also you can have more than one trigger.
If your need that your animation do something and after a time do something else you can use a debouncer function
_debouncer.run(() {
_onHandlerStateMachine()
});
**Remember update the view if are using state management
when the rive file is load
// Loads a Rive file
Future<void> _loadRiveFile() async {
final bytes = await rootBundle.load(riveFileName);
RiveFile rFile = RiveFile.import(bytes);
final artboard = rFile.mainArtboard;
_onRiveInit(artboard);
globalArtboard = artboard
..addController(
_animationController = SimpleAnimation('idle'),
);
}
Here I have and example of a Rive animation of Teddy, using Flutter with provider
https://github.com/alcampospalacios/flutter-rive-animations
I'm creating an audio player and I already have most of its functionality; however, I need the function to speed up the audio playback. I cannot find that function in the package I'm using.
If anyone knows of any tutorial on how to use this function to speed up the audio speed, I would appreciate it.
audio_service 0.17 and earlier
In the UI:
await AudioService.setSpeed(1.8); // 1.8x speed
In your background task:
#override
Future<void> onSetSpeed(double speed) => _audioPlayer.setSpeed(speed);
These work just like seekTo and onSeekTo in the project example (which you can use as a guide), except that the parameter represents the speed rather than the seek position.
audio_service 0.18 and later
In the UI:
await audioHandler.setSpeed(1.8); // 1.8x speed
In your audio handler:
#override
Future<void> setSpeed(double speed) => _audioPlayer.setSpeed(speed);
/// Sets the playback rate - call this after first calling play() or resume().
///
/// iOS and macOS have limits between 0.5 and 2x
/// Android SDK version should be 23 or higher.
/// not sure if that's changed recently.
Future<int> setPlaybackRate({double playbackRate = 1.0}) {
return _invokeMethod('setPlaybackRate', {'playbackRate': playbackRate});
}
you can try like this or not?
audioplayers: ^0.16.1