How to play playlist youtube video in flutter - flutter

I have playlist youtube videos list and I get id and url how to play playlist youtube videos by id or url with youtube_player_flutter
I tried but not worked.

you have to add youtube api to get metadata to your app. here is the link to get youtube API and get playlist : https://developers.google.com/youtube/v3/docs/playlists/list

If you are not gonna use Web, then you can use youtube_player_iframe. you dont need api.
inside State
YoutubePlayerController _controller = YoutubePlayerController(
initialVideoId: '1oF3pI5umck',
params: YoutubePlayerParams(
// Defining custom playlist
startAt: Duration(seconds: 30),
showControls: true,
showFullscreenButton: true,
),
);
#override
void dispose() {
super.dispose();
_controller.close();
}
and use it like
YoutubePlayerIFrame(
// gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{},
controller: _controller,
aspectRatio: 16 / 9,
),
),
here is full code: SO youtube_player_iframe

I think you can use, better_player for this. I have used it in Android and iOs and it works well but i don't know if it works on Web.
link: https://pub.dev/packages/better_player
for playlist documentation : https://jhomlala.github.io/betterplayer/#/playlistconfiguration

Related

Trying to navigate via HLS video in Flutter

I'm trying to navigate via HLS video. Navigation includes clicking -15 seconds and +15 seconds buttons, clicking on a video progress bar and playing video again when it reaches 30 seconds timestamp. I use Flutter, video_player package with chewie package. HLS is not traditional. I receive a big HLS from video archive: it's a .m3u8 playlist with one .ts file inside it. If I try to paste the url with .m3u8 playlist to the browser it starts to load it and it takes nearly all day.
void makePlayChecker() {
playerTimeChecker = Timer.periodic(Duration(seconds: 1), (timer) {
if (videoPlayerController.value.position > videoMaxLength) {
videoPlayerController.seekTo(Duration(seconds: 0));
}
});
}
Upper method checks whether the video has reached 30 seconds timestamp, if so, I try to navigate it to its beginning, but unfortunately the video just resume playing without any navigation.
Future<void> initializePlayer() async {
videoPlayerController = VideoPlayerController.network(
generatedUrl,
formatHint: VideoFormat.hls,
);
await Future.wait([
videoPlayerController.initialize()
]);
_createChewieController();
await videoPlayerController.play();
setState(() {});
}
void _createChewieController() {
_chewieController = ChewieController(
videoPlayerController: videoPlayerController,
autoPlay: true,
allowMuting: true,
progressIndicatorDelay: Duration(seconds: 0),
customControls: CustomCupertinoControls(
backgroundColor: Colors.blue,
iconColor: Colors.white,
),
overlay: MixinWrapper(child: Text("UserMixin", style: TextStyle(color: Colors.red),)),
allowPlaybackSpeedChanging: false,
hideControlsTimer: Duration(minutes: 5),
);
}
Upper methods initialize video player and chewie controllers
How could I navigate via HLS video?

How can I get the details of currently playing song in miniplayer?

I am working on a music player app in flutter.
I fetch the songs from devices using on_audio_query package and display them in listview. When I click on a song, i set the plylist of all songs and play the one thats clicked using just_audio package like this.
await player.setAudioSource(
ConcatenatingAudioSource(
useLazyPreparation: true,
shuffleOrder: DefaultShuffleOrder(),
children: allSongsList! // allSongsList is the list of
songs(on_audio_query)
.map((songModel) =>
AudioSource.uri(Uri.parse(songModel.data)))
.toList(),
),
initialIndex: index, // Listview Index
initialPosition: Duration.zero);
await item.player.play();
I want to show miniplayer at the bottom only when there is a song playing(paused),refresh the song descriptions,how do I get the song description(Artist/song)?
I will let you the implementation of the mini player widget for you, however, I will consider that I have a shouldMiniPlayerBeVisible, in the Scaffold of your page:
First, declare and initialize a shouldMiniPlayerBeVisible variable that will manage the show/hide of the mini player:
bool shouldMiniPlayerBeVisible = false;
and a currentAudio which will take the song and pass it in the mini player.
YourAudioModel currentAudio = YourAudioModel();
Here, I supposed that I have a simple YourAudioModel which will hold information about audio such as title, description, length, URL (or local) path ...
I recommend not setting it to null initially , you can initialize it with a placeholder YourAudioModel audio model that has some dummy data, or loading data information for example...
now in your Scaffold:
Scaffold(
floatingActionButton: Visibility(
visible: shouldMiniPlayerBeVisible,
child: shouldMiniPlayerBeVisible(songToPlay: currentAudio),
),
),
I will consider that you are using a StatefulWidget, but the steps are the same as you need just to get the idea of it to implement it in other state management solutions.
in the initState, you need to listen to the playerStateStream stream like this:
player.playerStateStream.listen((state) {
if (state.playing) {
shouldMiniPlayerBeVisible = true;
} else {
shouldMiniPlayerBeVisible = false;
}
setState(() {});
});
this basically will track if any audio is playing or not, then show the mini player based on it.
now before your run the await item.player.play();, set your currentAudio variable to the new audio which is running, you can do it with a function like this:
Future<void> playCurrentAudioANdShowItInMiniPlayer(YourAudioModel audio) async {
currentAudio = YourAudioModel;
await item.player.play();
}
now from your UI, for each item in ListView, you can just call the playCurrentAudioANdShowItInMiniPlayer method with its YourAudioModeland expect it to work fine.
from here, you should implement the actual mini player widget, and you will need also a custom Navigator widget so that mini player will be on the screen even if you navigated to other screens, well I faced this issue before and the miniplayer worked just really fine and good as I expected, I recommend you to use it.

Flutter video_player sound sometimes not in sync with video

I am having an issue with Flutter video_player where sometimes the video hangs and the sound is not in sync with the video. There is a delay of ~1 second between the video and sound. This only happens when playing certain videos, most videos are fine. I've checked that one of the affected videos is in the same format (mp4) as other videos and also have downloaded that video from my S3 bucket and have confirmed that it plays correctly in that case, so I believe it must be an issue with the video_player plugin. Here is my code to load the video controller. Is there any reason that videos would behave differently with this plugin where the audio and video are not in sync?
void loadVideo() async {
videoController =
VideoPlayerController.network(videoLink);
videoController.initialize().then((_) {
if (!mounted) {
// displays an error message if the video controller doesn't load
videoError = true;
setState(() {});
return;
}
setState(() {});
});
videoController.addListener(_listenForError);
}
void playVideo() async {
videoController.play();
}
Widget cameraWidget = Transform.scale(
scale: videoController.value.aspectRatio / deviceRatio,
child: AspectRatio(
aspectRatio: videoController.value.aspectRatio,
child: VideoPlayer(videoController),
),
);

Flutter Audio Cache Error with player.play

Hi this code works wonderfully with Angela in my Flutter course haha but for some reason the player.play('notes1.wav') isnt working for me.. tips? I'm getting this error..
error: The method 'play' isn't defined for the type 'Type'. (undefined_method at [xylophone] lib/main.dart:17)
import 'package:flutter/material.dart';
import 'package:audioplayers/audio_cache.dart';
void main() => runApp(XylophoneApp());
class XylophoneApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Center(
child: FlatButton(
onPressed: () {
final player = AudioCache;
player.play('note1.wav');
},
child: Text('Click Me'),
),
),
),
),
);
}
}
I'm working on the same course! You've got the opening/closing brackets missing on the AudioCache declaration. It should be:
final player = AudioCache();
I'd also do this for playing the audio, as it will stop making a sound after you press a few buttons:
player.play('note$note.wav',
mode: PlayerMode.LOW_LATENCY,
stayAwake: false);
It's better than the original code, but not perfect. I think there are audio 32 channels that get used up quite quickly - the about change seems to release them a bit quicker. Good luck with the rest of the course!
Migration Guide
dependencies: audioplayers: ^0.x.x
to
dependencies: audioplayers: ^1.0.1
https://github.com/bluefireteam/audioplayers/blob/main/migration_guide.md
AudioCache is dead, long live Sources One of the main changes was my desire to "kill" the AudioCache API due to the vast confusion that it caused with users (despite our best efforts documenting everything).
We still have the AudioCache class but its APIs are exclusively dedicated to transforming asset files into local files, cache them, and provide the path. It however doesn't normally need be used by end users because the AudioPlayer itself is now capable of playing audio from any Source.
What is a Source? It's a sealed class that can be one of:
UrlSource: get the audio from a remote URL from the Internet DeviceFileSource: access a file in the user's device, probably selected by a file picker AssetSource: play an asset bundled with your app, normally within the assets directory BytesSource (only some platforms): pass in the bytes of your audio directly (read it from anywhere). If you use AssetSource, the AudioPlayer will use its instance of AudioCache (which defaults to the global cache if unchanged) automatically. This unifies all playing APIs under AudioPlayer and entirely removes the AudioCache detail for most users.
AudioCache is obsolete now, try this
import 'package:audioplayers/audioplayers.dart';
final player = AudioPlayer();
player.play(AssetSource('note1.wav'));
AudioCache is deprecated. It will not work now.
Instead use this code:
child: TextButton(
onPressed: () async {
final player = AudioPlayer();
await player.play(
AssetSource('note1.wav'),
);
},
child: Text("Play me"),
),

Playing videos with flutter web and firebase storage

I am trying to make a website in which the user can add videos and also see these videos. All of them are stored in firebase storage. This is how I store it
fb.StorageReference storageRef = fb.storage().ref('videos/$chapter)');
fb.UploadTaskSnapshot uploadTaskSnapshot = await storageRef.put(videoFile, fb.UploadMetadata(contentType: 'video/mp4')).future;
await uploadTaskSnapshot.ref.getDownloadURL().then((value){
videoUrl = value.toString();
});
snapshot.reference.collection("videos").add({
"chapter":chapter,
"class":grade,
"description":description,
"notes":notes,
"subject":subject,
"video":videoUrl,
"timestamp":DateTime.now().millisecondsSinceEpoch.toString()
});
And I play them using the normal video player plugin. Now the problem is when I store it, I get a url like
https://firebasestorage.googleapis.com/v0/b/studyme-me.appspot.com/o/videos%2Ff)?alt=media&token=ec4fea39-032b-438f-8122-f8e042c1c9c7
But the video player in flutter web requires a .mp4 or .wav or something like that file. What can I do that can either allow the video player to play these (I don't think its possible) or I can get the .mp4 file for this. Maybe I can use firebase storage to open this url and get it but I dont know how
Any suggestions would be appreciated
You can use the VideoPlayerController plugin to do that
VideoPlayerController controller = VideoPlayerController.network('your-video-url',);
//Play/Pause Video:
FloatingActionButton(
onPressed: () {
// Wrap the play or pause in a call to `setState`. This ensures the
// correct icon is shown
setState(() {
// If the video is playing, pause it.
if (_controller.value.isPlaying) {
_controller.pause();
} else {
// If the video is paused, play it.
_controller.play();
}
});
},
// Display the correct icon depending on the state of the player.
child: Icon(
_controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
),
)
'''
more examples in the link above