Skip to content

Commit

Permalink
fixed the inconsistency of song play and showed
Browse files Browse the repository at this point in the history
  • Loading branch information
sheikhhaziq committed Jan 4, 2023
1 parent f0ce8c5 commit 973987a
Show file tree
Hide file tree
Showing 7 changed files with 316 additions and 193 deletions.
180 changes: 121 additions & 59 deletions lib/providers/MusicPlayer.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import 'dart:developer';

import 'dart:async';
// import 'dart:developer';
// _player.sequenceState?.effectiveSequence
// .map((e) => e.tag.extras['track'] as Track)
// .toList()
import 'package:flutter/cupertino.dart';
import 'package:just_audio/just_audio.dart';
import 'package:just_audio_background/just_audio_background.dart';
Expand All @@ -18,8 +21,10 @@ class MusicPlayer extends ChangeNotifier {
int _index = 0;
bool _initialised = false;
bool _isPlaying = false;
List<Track> _songs = [];
MiniplayerController _miniplayerController = MiniplayerController();

Track? tempSong;
final MiniplayerController _miniplayerController = MiniplayerController();
StreamController<bool> _cancelController = StreamController<bool>();

PaletteGenerator? _color;
ConcatenatingAudioSource? playlist = ConcatenatingAudioSource(
Expand All @@ -40,6 +45,10 @@ class MusicPlayer extends ChangeNotifier {
_index = event ?? _index;
notifyListeners();
});
_player.sequenceStream.listen((event) {
notifyListeners();
});

_player.loopModeStream.listen((event) {
notifyListeners();
});
Expand All @@ -52,98 +61,129 @@ class MusicPlayer extends ChangeNotifier {

get player => _player;
get isInitialized => _initialised;

get miniplayerController => _miniplayerController;
get song {
if (_songs.isEmpty) {
return null;
} else if (_player.currentIndex == null) {
return _songs[0];
} else if (_player.currentIndex! >= _songs.length) {
return _songs[0];
} else {
return _songs[_player.currentIndex!];
}
}
Track? get song => _player.sequenceState?.currentSource?.tag.extras == null
? tempSong
: Track.fromMap(_player.sequenceState?.currentSource?.tag.extras);

get songs =>
_player.sequence?.map((e) => Track.fromMap(e.tag.extras)).toList() ?? [];

get songs => _songs;
get color => _color;
get isPlaying => _isPlaying;

addToQUeue(Track newSong) async {
bool exists = _player.sequence
?.where((element) => element.tag.id == newSong.videoId)
.isNotEmpty ??
false;
if (exists) {
return;
}
PaletteGenerator? color = await generateColor(newSong.thumbnails.last.url);
newSong.colorPalette = ColorPalette(
darkMutedColor: color?.darkMutedColor?.color,
lightMutedColor: color?.lightMutedColor?.color);
_songs.add(newSong);
_initialised = true;
notifyListeners();
playlist?.add(
playlist
?.add(
AudioSource.uri(
await getAudioUri(newSong.videoId),
tag: MediaItem(
id: newSong.videoId,
title: newSong.title,
artUri: Uri.parse(newSong.thumbnails.last.url),
artist: newSong.artists.first.name,
extras: newSong.toMap(),
),
),
);
)
.then((value) {
tempSong = null;
notifyListeners();
});
}

setPlayer() async {
Future setPlayer() async {
await _player.stop();
playlist!.clear();
_songs.clear();
playlist = null;
playlist = ConcatenatingAudioSource(
useLazyPreparation: true,
shuffleOrder: DefaultShuffleOrder(),
children: [],
);
// _songs.clear();

_player.setAudioSource(playlist!,
await _player.setAudioSource(playlist!,
initialIndex: 0, initialPosition: Duration.zero, preload: false);
}

addNew(Track newSong) async {
if (newSong.videoId == _player.sequenceState?.currentSource?.tag.id) {
_miniplayerController.animateToHeight(state: PanelState.MAX);
return;
}
_cancelController.sink.add(true);
_cancelController = StreamController<bool>();
try {
PaletteGenerator? color =
await generateColor(newSong.thumbnails.last.url);
newSong.colorPalette = ColorPalette(
darkMutedColor: color?.darkMutedColor?.color,
lightMutedColor: color?.lightMutedColor?.color);

tempSong = newSong;
await setPlayer();

_songs = [newSong];

_initialised = true;

notifyListeners();
_miniplayerController.animateToHeight(state: PanelState.MAX);

await playlist?.add(AudioSource.uri(
_player.play();

await playlist
?.add(AudioSource.uri(
await getAudioUri(newSong.videoId),
tag: MediaItem(
id: newSong.videoId,
title: newSong.title,
artUri: Uri.parse(newSong.thumbnails.last.url),
artist: newSong.artists.first.name,
album: newSong.albums?.name,
extras: newSong.toMap(),
),
));
))
.then((value) {
tempSong = null;
_miniplayerController.animateToHeight(state: PanelState.MAX);
notifyListeners();
});

_player.play();
await HomeApi.getWatchPlaylist(newSong.videoId, 10)
.then((List value) async {
List tracks = value;
_songs[0].thumbnails.last.url = tracks[0]['thumbnail'].last['url'];
// _songs[0].thumbnails.last.url = tracks[0]['thumbnail'].last['url'];
tracks.removeAt(0);
for (var track in tracks) {
if (playlist == null || playlist!.length >= 10) {
break;

bool breakIt = false;
_cancelController.stream.first.then((cancelled) async {
if (cancelled) {
breakIt = true;
}
try {
track['thumbnails'] = track['thumbnail'];
Track tr = Track.fromMap(track);
await addToQUeue(tr);
} catch (e) {
log(e.toString());
});
for (Map<String, dynamic> track in tracks) {
// If the loop has been cancelled, exit

if (breakIt) {
break;
}

// Add the item to the otherSongs list

track['thumbnails'] = track['thumbnail'];
Track tr = Track.fromMap(track);
await addToQUeue(tr);
}
});
return true;
Expand All @@ -153,31 +193,54 @@ class MusicPlayer extends ChangeNotifier {
}

Future addPlayList(List newSongs) async {
_cancelController.sink.add(true);
_cancelController = StreamController<bool>();
tempSong = Track.fromMap(newSongs[0]);
Track newSong = Track.fromMap(newSongs[0]);

PaletteGenerator? color = await generateColor(newSong.thumbnails.last.url);
newSong.colorPalette = ColorPalette(
darkMutedColor: color?.darkMutedColor?.color,
lightMutedColor: color?.lightMutedColor?.color);
tempSong = newSong;
await setPlayer();

_initialised = true;
setPlayer();
int i = 0;
for (Map<String, dynamic> nSong in newSongs) {
if (playlist != null) {
Track newSong = Track.fromMap(nSong);
await addToQUeue(newSong);
if (i == 0) {
_player.play();
_miniplayerController.animateToHeight(state: PanelState.MAX);
}
notifyListeners();
_miniplayerController.animateToHeight(state: PanelState.MAX);

_player.play();

bool breakIt = false;
_cancelController.stream.first.then((cancelled) async {
if (cancelled) {
breakIt = true;
}
});

i += 1;
} else {
for (Map<String, dynamic> nSong in newSongs) {
// If the loop has been cancelled, exit
if (breakIt) {
break;
}

// Add the item to the otherSongs list
Track newSong = Track.fromMap(nSong);
await addToQUeue(newSong);
}
}

/// Change the songe position in playlist from one index to another.
moveTo(index, newIndex) {
Track song = _songs.removeAt(index);
_songs.insertAll(newIndex, [song]);
playlist?.move(index, newIndex);
moveTo(index, newIndex) async {
// Track song = _songs.removeAt(index);
// _songs.insertAll(newIndex, [song]);
await playlist?.move(index, newIndex);
notifyListeners();
}

removeAt(index) async {
await playlist?.removeAt(index);
notifyListeners();
}

Expand All @@ -203,7 +266,7 @@ class MusicPlayer extends ChangeNotifier {
if (!_player.playing) _player.play();
}

/// Play the previous song in the playlist. If the current song is first one, nothing will happen.
/// Play the previous item, or does nothing if there is no previous item.
previous() {
_player.seekToPrevious();
if (!_player.playing) _player.play();
Expand All @@ -226,8 +289,7 @@ class MusicPlayer extends ChangeNotifier {
: (audios.length / 2).floor());

audioUrl = audios[audioNumber].url.toString();
// log(audios[audioNumber].size.totalMegaBytes.toString());
// log(audioQuality);

return Uri.parse(audioUrl);
} catch (e) {
return Uri();
Expand Down
23 changes: 22 additions & 1 deletion lib/screens/FavouriteScreen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,28 @@ class FavouriteScreen extends StatelessWidget {
return ListView(
children: favourites.map((track) {
Map<String, dynamic> newMap = jsonDecode(jsonEncode(track));
return TrackTile(track: newMap);

return Dismissible(
direction: DismissDirection.endToStart,
key: Key("$newMap['videoId']"),
onDismissed: (direction) {
box.delete(newMap['videoId']);
},
background: Container(
color: Colors.red,
child: Center(
child: Text(
"Remove from Favourites",
style: Theme.of(context)
.primaryTextTheme
.bodyLarge
?.copyWith(
color: Colors.white, fontWeight: FontWeight.bold),
),
),
),
child: TrackTile(track: newMap),
);
}).toList(),
);
},
Expand Down
6 changes: 5 additions & 1 deletion lib/screens/HomeScreen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,11 @@ class _HomeScreenState extends State<HomeScreen>
crossAxisAlignment:
CrossAxisAlignment.start,
children: content
.sublist(0, 5)
.sublist(
0,
content.length > 5
? 5
: content.length)
.map((track) {
return TrackTile(track: track);
}).toList()),
Expand Down
5 changes: 4 additions & 1 deletion lib/screens/MainScreen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ class _MainScreenState extends State<MainScreen> {
Widget build(BuildContext context) {
bool isDarkTheme =
context.watch<ThemeProvider>().themeMode == ThemeMode.dark;

return Scaffold(
body: LayoutBuilder(builder: (context, constraints) {
return Column(
Expand Down Expand Up @@ -109,7 +110,9 @@ class _MainScreenState extends State<MainScreen> {
),
Opacity(
opacity: 1 - (percentage),
child: const PanelHeader()),
child: PanelHeader(
song: context.watch<MusicPlayer>().song!,
)),
],
);
}),
Expand Down
Loading

0 comments on commit 973987a

Please sign in to comment.