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

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.

Related

Go back to previous page in flutter

I have a flutter app that connects via bluetooth with a device by pressing on the device name from the list of paired devices. This is the coding :
final BluetoothDevice server;
DataCollectionPage({required this.server});
...............................................................................
child: ListView(
children: devices
.map((_device)=> BluetoothDeviceListEntry(
device: _device,
enabled: true,
onTap: (){
if (kDebugMode) {
print("item");
}
_startDataCollection(context, _device);
},
................................................................................
void _startDataCollection(BuildContext context, BluetoothDevice server){
Navigator.of(context).push(MaterialPageRoute(builder: (context){
return DataCollectionPage(server: server);
}));
}
Then once I navigate to the "DataCollectionPage" page, I perform some actions and data collection methods and at the end I will be in other page named "DataCollectionTimer". In this page a timer will be displayed on the screen for few seconds then at the end of this timer a Dialog will show to give some message and then finally Once I press the button close on this dialog, I want to go back to DataCollectionPage. So If I try to use
MaterialPageRoute( builder: (context) => DataCollectionPage(), ),
It will give an error because parameter 'server' is required which I obtained from the list of paired devices that was in a different class.
Is there a way to go back to DataCollectionPage from the current one without going all the way back to the page where the list of paired devices is there.
Thank you in advance
You need to make the server field optional and then use popUntil
final BluetoothDevice? server;
DataCollectionPage({this.server});

How to identify if the controls has gone or not in flutter chewie video player

I am working on a flutter app and using chewie videoplayer plugin.So when we started playing a video it shows controls at bottom and after few seconds it vanishes and when we move the mouse again it shows again. so is there any method to find when the controls are shown on screen and when its not shown.
actually i am giving close button on the video player. but it doesnt vanishes with those video player controls. it still stay on screen so to hide that close button along with video controls i need to get which process hides the control.
Please help me...
This process is inside the source code of chewie player. So if you need to customize and synchronise your own custom controls and options, either you have to explicitly fetch the source code and edit in that or you need to make your own controllers from scratch using video_player package as the core.
You need to customize the source code of the chewie player.
You can find MaterialControl class inside the source code of this package there is a function called _buildHitArea() just change notifier.hideStuff boolean according to your preference.
Widget _buildHitArea() {
final bool isFinished = _latestValue.position >= _latestValue.duration;
final bool showPlayButton = widget.showPlayButton && !_dragging && !notifier.hideStuff;
return GestureDetector(
onTap: () {
if (_latestValue.isPlaying) {
if (_displayTapped) {
setState(() {
notifier.hideStuff = false;
});
} else {
_cancelAndRestartTimer();
}
} else {
_playPause();
setState(() {
notifier.hideStuff = false;
});
}
},
child: CenterPlayButton(
backgroundColor: Colors.black54,
iconColor: Colors.white,
isFinished: isFinished,
isPlaying: controller.value.isPlaying,
show: showPlayButton,
onPressed: _playPause,
),
);
}

Flutter how to get current duration time in assets_audio_player

I am previously using just_audio and I am taking the current time like this
player.positionStream.listen((event) {
playerTimeNow = event;
updatePlayerBar();
});
Now I need to know how can I get time in this assets_audio_player
What I understood from your question is that you want the current playing position of the audio and want to update your player bar. For that you can use currentPosition property of AssetAudioPlayer which returns ValueStream. Yon can either listen to the currentPosition Stream or use it in StreamBuilder.
Simply listen to the currentPosition Stream :
assetsAudioPlayer.currentPosition.listen((positionValue){
playerTimeNow = positionValue;
updatePlayerBar();
});
Or you can also use StreamBuilder:
return StreamBuilder(
stream: assetsAudioPlayer.currentPosition,
builder: (context, asyncSnapshot) {
final Duration duration = asyncSnapshot.data;
return Text(duration.toString());
}),
Wrap the Widget which you want to provide the current audio position in StreamBuilder and use the values received from asyncSnapshot.data.
For Custom Notification :
Use Audio to customize Notification :
final audio = Audio("/assets/audio/country.mp3",
metas: Metas(
title: "Country",
artist: "Florent Champigny",
album: "CountryAlbum",
image: MetasImage.asset("assets/images/country.jpg"), //can be MetasImage.network
),
);
and pass it to assetsAudioPlayer.open(audio, showNotification: true);
Use Assets Audio Player package on pub dev instead.
It provides notification controls without any additional implementation.
An alternative plugin is Audio Player.
I would suggest you to take a look at this article: https://itnext.io/create-an-awesome-background-running-music-player-like-amazon-music-in-flutter-341a59efa936
It has an example about how to combine both packages.

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

Track progress Flutter video player

Hi I'm using the flutter video player plugin, I have something similar like this [{phrase:"something", startAt: 1039}, {phrase:"other somthing", startAt: 26500}] is there a way to change in ui the phrase based on the start time while the video is playing.
I have try to use a timer with a duration of 100 ms but I retrieve no exact time from the Flutter video player plugin.
You probably want to take a look at stateful widgets as they allow you to do exactly this. In short, you can set phrase to be some variable and once the video starts you can call setState and change the variable. Flutter will automatically redraw the widget and the text will be updated.
To determine if the video player is playing you can add a listener to your video controller.
_controller = VideoPlayerController.network(
'http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_20mb.mp4',
)
..addListener(() {
final bool isPlaying = _controller.value.isPlaying;
if (isPlaying != _isPlaying) {
setState(() {
_isPlaying = isPlaying;
});
}
})
..initialize().then((_) {
// Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
setState(() {});
});