This repository has been archived by the owner on Jan 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 849
/
lyric.dart
659 lines (559 loc) · 17.9 KB
/
lyric.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
import 'dart:convert';
import 'dart:ui' as ui;
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:quiet/component/utils/utils.dart';
const _kEnablePaintDebug = false;
class Lyric extends StatefulWidget {
Lyric({
required this.lyric,
this.lyricLineStyle,
this.position,
this.textAlign = TextAlign.center,
this.highlight = Colors.red,
required this.size,
this.onTap,
required this.playing,
}) : assert(lyric.size > 0);
final TextStyle? lyricLineStyle;
final LyricContent lyric;
final TextAlign textAlign;
final int? position;
final Color? highlight;
final Size size;
final VoidCallback? onTap;
/// player is playing
final bool playing;
@override
State<StatefulWidget> createState() => LyricState();
}
class LyricState extends State<Lyric> with TickerProviderStateMixin {
LyricPainter? lyricPainter;
AnimationController? _flingController;
AnimationController? _lineController;
//歌词色彩渐变动画
AnimationController? _gradientController;
@override
void initState() {
super.initState();
lyricPainter = LyricPainter(
widget.lyricLineStyle!,
widget.lyric,
textAlign: widget.textAlign,
highlight: widget.highlight,
);
_scrollToCurrentPosition(widget.position);
}
@override
void didUpdateWidget(Lyric oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.lyric != oldWidget.lyric) {
lyricPainter = LyricPainter(
widget.lyricLineStyle!,
widget.lyric,
textAlign: widget.textAlign,
highlight: widget.highlight,
);
}
if (widget.position != oldWidget.position) {
_scrollToCurrentPosition(widget.position);
}
if (widget.playing != oldWidget.playing) {
if (!widget.playing) {
_gradientController?.stop();
} else {
_gradientController?.forward();
}
}
}
/// scroll lyric to current playing position
void _scrollToCurrentPosition(int? milliseconds, {bool animate = true}) {
if (lyricPainter!.height == -1) {
WidgetsBinding.instance?.addPostFrameCallback((d) {
// debugPrint("try to init scroll to position ${widget.position.value},"
// "but lyricPainter is unavaiable, so scroll(without animate) on next frame $d");
//TODO maybe cause bad performance
if (mounted) _scrollToCurrentPosition(milliseconds, animate: false);
});
return;
}
final int line = widget.lyric
.findLineByTimeStamp(milliseconds!, lyricPainter!.currentLine);
if (lyricPainter!.currentLine != line && !dragging) {
final double offset = lyricPainter!.computeScrollTo(line);
if (animate) {
_lineController?.dispose();
_lineController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 800),
)..addStatusListener((status) {
if (status == AnimationStatus.completed) {
_lineController!.dispose();
_lineController = null;
}
});
final Animation<double> animation = Tween<double>(
begin: lyricPainter!.offsetScroll,
end: lyricPainter!.offsetScroll + offset)
.chain(CurveTween(curve: Curves.easeInOut))
.animate(_lineController!);
animation.addListener(() {
lyricPainter!.offsetScroll = animation.value;
});
_lineController!.forward();
} else {
lyricPainter!.offsetScroll += offset;
}
_gradientController?.dispose();
final entry = widget.lyric[line];
final startPercent = (milliseconds - entry.position) / entry.duration;
_gradientController = AnimationController(
vsync: this,
duration: Duration(
milliseconds: (entry.duration * (1 - startPercent)).toInt()),
);
_gradientController!.addListener(() {
lyricPainter!.lineGradientPercent = _gradientController!.value;
});
if (widget.playing) {
_gradientController!.forward(from: startPercent);
} else {
_gradientController!.value = startPercent;
}
}
lyricPainter!.currentLine = line;
}
bool dragging = false;
bool _consumeTap = false;
@override
void dispose() {
_flingController?.dispose();
_flingController = null;
_lineController?.dispose();
_lineController = null;
_gradientController?.dispose();
_gradientController = null;
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container(
constraints: const BoxConstraints(minWidth: 300, minHeight: 120),
child: _ScrollerListener(
onScroll: (delta) {
lyricPainter!.offsetScroll += -delta;
},
child: GestureDetector(
onTap: () {
if (!_consumeTap && widget.onTap != null) {
widget.onTap!();
} else {
_consumeTap = false;
}
},
onTapDown: (details) {
if (dragging) {
_consumeTap = true;
dragging = false;
_flingController?.dispose();
_flingController = null;
}
},
onVerticalDragStart: (details) {
dragging = true;
_flingController?.dispose();
_flingController = null;
},
onVerticalDragUpdate: (details) {
lyricPainter!.offsetScroll += details.primaryDelta!;
},
onVerticalDragEnd: (details) {
_flingController = AnimationController.unbounded(
vsync: this,
duration: const Duration(milliseconds: 300),
)
..addListener(() {
double value = _flingController!.value;
if (value < -lyricPainter!.height || value >= 0) {
_flingController!.dispose();
_flingController = null;
dragging = false;
value = value.clamp(-lyricPainter!.height, 0.0);
}
lyricPainter!.offsetScroll = value;
lyricPainter!.repaint();
})
..addStatusListener((status) {
if (status == AnimationStatus.completed ||
status == AnimationStatus.dismissed) {
dragging = false;
_flingController?.dispose();
_flingController = null;
}
})
..animateWith(ClampingScrollSimulation(
position: lyricPainter!.offsetScroll,
velocity: details.primaryVelocity!));
},
child: CustomPaint(
size: widget.size,
painter: lyricPainter,
),
),
),
);
}
}
class _ScrollerListener extends StatefulWidget {
const _ScrollerListener({
Key? key,
required this.child,
required this.onScroll,
this.axisDirection = AxisDirection.down,
}) : super(key: key);
final Widget child;
final void Function(double offset) onScroll;
final AxisDirection axisDirection;
@override
State<_ScrollerListener> createState() => _ScrollerListenerState();
}
class _ScrollerListenerState extends State<_ScrollerListener> {
@override
Widget build(BuildContext context) {
return Listener(
onPointerSignal: _receivedPointerSignal,
child: widget.child,
);
}
void _receivedPointerSignal(PointerSignalEvent event) {
if (event is PointerScrollEvent) {
if (_pointerSignalEventDelta(event) != 0.0) {
GestureBinding.instance!.pointerSignalResolver
.register(event, _handlePointerScroll);
}
}
}
void _handlePointerScroll(PointerEvent event) {
assert(event is PointerScrollEvent);
final double delta = _pointerSignalEventDelta(event as PointerScrollEvent);
final double scrollerScale;
if (defaultTargetPlatform == TargetPlatform.windows) {
scrollerScale = window.devicePixelRatio * 2;
} else if (defaultTargetPlatform == TargetPlatform.linux) {
scrollerScale = window.devicePixelRatio;
} else {
scrollerScale = 1;
}
widget.onScroll(delta * scrollerScale);
}
// Returns the delta that should result from applying [event] with axis and
// direction taken into account.
double _pointerSignalEventDelta(PointerScrollEvent event) {
double delta = event.scrollDelta.dy;
if (axisDirectionIsReversed(widget.axisDirection)) {
delta *= -1;
}
return delta;
}
}
class LyricPainter extends ChangeNotifier implements CustomPainter {
///param lyric must not be null
LyricPainter(
TextStyle style,
this.lyric, {
this.textAlign = TextAlign.center,
Color? highlight = Colors.red,
}) {
lyricPainters = [];
for (int i = 0; i < lyric.size; i++) {
final painter = TextPainter(
text: TextSpan(style: style, text: lyric[i].line),
textAlign: textAlign);
painter.textDirection = TextDirection.ltr;
// painter.layout();//layout first, to get the height
lyricPainters.add(painter);
}
_styleHighlight = style.copyWith(color: highlight);
}
LyricContent lyric;
late List<TextPainter> lyricPainters;
final TextPainter _highlightPainter =
TextPainter(textDirection: TextDirection.ltr);
double _offsetScroll = 0;
double get offsetScroll => _offsetScroll;
double _lineGradientPercent = -1;
double get lineGradientPercent {
if (_lineGradientPercent == -1) return 1.0;
return _lineGradientPercent.clamp(0.0, 1.0);
}
///音乐播放时间,毫秒
set lineGradientPercent(double percent) {
_lineGradientPercent = percent;
repaint();
}
set offsetScroll(double value) {
if (height == -1) {
// do not change offset when height is not available.
return;
}
_offsetScroll = value.clamp(-height, 0.0);
repaint();
}
int currentLine = 0;
TextAlign textAlign;
TextStyle? _styleHighlight;
void repaint() {
notifyListeners();
}
double get height => _height;
double _height = -1;
@override
void paint(ui.Canvas canvas, ui.Size size) {
_layoutPainterList(size);
canvas.clipRect(Rect.fromLTWH(0, 0, size.width, size.height));
//当offsetScroll为0时,第一行绘制在正中央
double dy = offsetScroll + size.height / 2 - lyricPainters[0].height / 2;
for (int line = 0; line < lyricPainters.length; line++) {
final TextPainter painter = lyricPainters[line];
if (line == currentLine) {
_paintCurrentLine(canvas, painter, dy, size);
} else {
drawLine(canvas, painter, dy, size);
}
dy += painter.height;
}
}
//绘制当前播放中的歌词
void _paintCurrentLine(
ui.Canvas canvas, TextPainter painter, double dy, ui.Size size) {
if (dy > size.height || dy < 0 - painter.height) {
return;
}
//for current highlight line, draw background text first
drawLine(canvas, painter, dy, size);
_highlightPainter
..text = TextSpan(
text: (painter.text as TextSpan?)?.text, style: _styleHighlight)
..textAlign = textAlign;
_highlightPainter.layout(); //layout with unbound width
double lineWidth = _highlightPainter.width;
double gradientWidth = _highlightPainter.width * lineGradientPercent;
final double lineHeight = _highlightPainter.height;
_highlightPainter.layout(maxWidth: size.width);
final highlightRegion = Path();
double lineDy = 0;
while (gradientWidth > 0) {
double dx = 0;
if (lineWidth < size.width) {
dx = (size.width - lineWidth) / 2;
}
highlightRegion.addRect(
Rect.fromLTWH(0, dy + lineDy, dx + gradientWidth, lineHeight));
lineWidth -= _highlightPainter.width;
gradientWidth -= _highlightPainter.width;
lineDy += lineHeight;
}
canvas.save();
canvas.clipPath(highlightRegion);
drawLine(canvas, _highlightPainter, dy, size);
canvas.restore();
assert(() {
if (_kEnablePaintDebug) {
final painter = Paint()
..color = Colors.black
..style = PaintingStyle.stroke
..strokeWidth = 1;
canvas.drawPath(highlightRegion, painter);
}
return true;
}());
}
///draw a lyric line
void drawLine(
ui.Canvas canvas, TextPainter painter, double dy, ui.Size size) {
if (dy > size.height || dy < 0 - painter.height) {
return;
}
canvas.save();
canvas.translate(_calculateAlignOffset(painter, size), dy);
painter.paint(canvas, Offset.zero);
canvas.restore();
}
double _calculateAlignOffset(TextPainter painter, ui.Size size) {
if (textAlign == TextAlign.center) {
return (size.width - painter.width) / 2;
}
return 0;
}
@override
bool shouldRepaint(LyricPainter oldDelegate) {
return true;
}
void _layoutPainterList(ui.Size size) {
_height = 0;
for (final p in lyricPainters) {
p.layout(maxWidth: size.width);
_height += p.height;
}
}
//compute the offset current offset to destination line
double computeScrollTo(int destination) {
if (lyricPainters.isEmpty || this.height == 0) {
return 0;
}
double height = -lyricPainters[0].height / 2;
for (int i = 0; i < lyricPainters.length; i++) {
if (i == destination) {
height += lyricPainters[i].height / 2;
break;
}
height += lyricPainters[i].height;
}
return -(height + offsetScroll);
}
@override
bool? hitTest(ui.Offset position) => null;
@override
SemanticsBuilderCallback? get semanticsBuilder => null;
@override
bool shouldRebuildSemantics(CustomPainter oldDelegate) =>
shouldRepaint(oldDelegate as LyricPainter);
}
class LyricContent {
LyricContent.from(String text) {
final List<String> lines = _kLineSplitter.convert(text);
final Map map = <int, String>{};
for (final line in lines) {
LyricEntry.inflate(line, map as Map<int, String>);
}
final List<int> keys = map.keys.toList() as List<int>..sort();
for (var i = 0; i < keys.length; i++) {
final key = keys[i];
_durations.add(key);
int duration = _kDefaultLineDuration;
if (i + 1 < keys.length) {
duration = keys[i + 1] - key;
}
_lyricEntries.add(LyricEntry(map[key], key, duration));
}
}
///splitter lyric content to line
static const LineSplitter _kLineSplitter = LineSplitter();
//默认歌词持续时间
static const int _kDefaultLineDuration = 5 * 1000;
final List<int> _durations = [];
final List<LyricEntry> _lyricEntries = [];
int get size => _durations.length;
LyricEntry operator [](int index) {
return _lyricEntries[index];
}
int _getTimeStamp(int index) {
return _durations[index];
}
LyricEntry? getLineByTimeStamp(final int timeStamp, final int anchorLine) {
if (size <= 0) {
return null;
}
final line = findLineByTimeStamp(timeStamp, anchorLine);
return this[line];
}
///
///根据时间戳来寻找匹配当前时刻的歌词
///
///@param timeStamp 歌词的时间戳(毫秒)
///@param anchorLine the start line to search
///@return index to getLyricEntry
///
int findLineByTimeStamp(final int timeStamp, final int anchorLine) {
int position = anchorLine;
if (position < 0 || position > size - 1) {
position = 0;
}
if (_getTimeStamp(position) > timeStamp) {
// look forward
// ignore: invariant_booleans
while (_getTimeStamp(position) > timeStamp) {
position--;
if (position <= 0) {
position = 0;
break;
}
}
} else {
while (_getTimeStamp(position) < timeStamp) {
position++;
if (position <= size - 1 && _getTimeStamp(position) > timeStamp) {
position--;
break;
}
if (position >= size - 1) {
position = size - 1;
break;
}
}
}
return position;
}
@override
String toString() {
return 'Lyric{_lyricEntries: $_lyricEntries}';
}
}
class LyricEntry {
LyricEntry(this.line, this.position, this.duration)
: timeStamp = getTimeStamp(position);
static RegExp pattern = RegExp(r"\[\d{2}:\d{2}.\d{2,3}]");
static int _stamp2int(final String stamp) {
final int indexOfColon = stamp.indexOf(":");
final int indexOfPoint = stamp.indexOf(".");
final int minute = int.parse(stamp.substring(1, indexOfColon));
final int second =
int.parse(stamp.substring(indexOfColon + 1, indexOfPoint));
int millisecond;
if (stamp.length - indexOfPoint == 2) {
millisecond =
int.parse(stamp.substring(indexOfPoint + 1, stamp.length)) * 10;
} else {
millisecond =
int.parse(stamp.substring(indexOfPoint + 1, stamp.length - 1));
}
return (((minute * 60) + second) * 1000) + millisecond;
}
///build from a .lrc file line .such as: [11:44.100] what makes your beautiful
static void inflate(String line, Map<int, String> map) {
//TODO lyric info
if (line.startsWith("[ti:")) {
} else if (line.startsWith("[ar:")) {
} else if (line.startsWith("[al:")) {
} else if (line.startsWith("[au:")) {
} else if (line.startsWith("[by:")) {
} else {
final stamps = pattern.allMatches(line);
final content = line.split(pattern).last;
for (final stamp in stamps) {
final int timeStamp = _stamp2int(stamp.group(0)!);
map[timeStamp] = content;
}
}
}
final String timeStamp;
final String? line;
final int position;
///the duration of this line
final int duration;
@override
String toString() {
return 'LyricEntry{line: $line, timeStamp: $timeStamp}';
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is LyricEntry &&
runtimeType == other.runtimeType &&
line == other.line &&
timeStamp == other.timeStamp;
@override
int get hashCode => line.hashCode ^ timeStamp.hashCode;
}