-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathAudioPlayer.dart
495 lines (462 loc) · 14.6 KB
/
AudioPlayer.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
// Import the latest package of flutter audio player
//audioplayers: ^0.19.1 (latest as of now)
import 'dart:async';
import 'dart:io';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import 'player_widget.dart';
typedef OnError = void Function(Exception exception);
const kUrl1 = 'https://luan.xyz/files/audio/ambient_c_motion.mp3';
const kUrl2 = 'https://luan.xyz/files/audio/nasa_on_a_mission.mp3';
const kUrl3 = 'http://bbcmedia.ic.llnwd.net/stream/bbcmedia_radio1xtra_mf_p';
void main() {
runApp(MaterialApp(home: ExampleApp()));
}
class ExampleApp extends StatefulWidget {
@override
_ExampleAppState createState() => _ExampleAppState();
}
class _ExampleAppState extends State<ExampleApp> {
AudioCache audioCache = AudioCache();
AudioPlayer advancedPlayer = AudioPlayer();
String? localFilePath;
String? localAudioCacheURI;
@override
void initState() {
super.initState();
if (kIsWeb) {
// Calls to Platform.isIOS fails on web
return;
}
if (Platform.isIOS) {
audioCache.fixedPlayer?.notificationService.startHeadlessService();
advancedPlayer.notificationService.startHeadlessService();
}
}
Future _loadFile() async {
final bytes = await readBytes(Uri.parse(kUrl1));
final dir = await getApplicationDocumentsDirectory();
final file = File('${dir.path}/audio.mp3');
await file.writeAsBytes(bytes);
if (file.existsSync()) {
setState(() => localFilePath = file.path);
}
}
Widget remoteUrl() {
return const SingleChildScrollView(
child: _Tab(
children: [
Text(
'Sample 1 ($kUrl1)',
key: Key('url1'),
style: TextStyle(fontWeight: FontWeight.bold),
),
PlayerWidget(url: kUrl1),
Text(
'Sample 2 ($kUrl2)',
style: TextStyle(fontWeight: FontWeight.bold),
),
PlayerWidget(url: kUrl2),
Text(
'Sample 3 ($kUrl3)',
style: TextStyle(fontWeight: FontWeight.bold),
),
PlayerWidget(url: kUrl3),
Text(
'Sample 4 (Low Latency mode) ($kUrl1)',
style: TextStyle(fontWeight: FontWeight.bold),
),
PlayerWidget(url: kUrl1, mode: PlayerMode.LOW_LATENCY),
],
),
);
}
Widget localFile() {
return _Tab(children: [
const Text(' -- manually load bytes (no web!) --'),
const Text('File: $kUrl1'),
_Btn(txt: 'Download File to your Device', onPressed: _loadFile),
Text('Current local file path: $localFilePath'),
if (localFilePath != null) PlayerWidget(url: localFilePath!),
Container(
constraints: const BoxConstraints.expand(width: 1.0, height: 20.0),
),
const Text(' -- via AudioCache --'),
const Text('File: $kUrl2'),
_Btn(txt: 'Download File to your Device', onPressed: _loadFileAC),
Text('Current AC loaded: $localAudioCacheURI'),
if (localAudioCacheURI != null) PlayerWidget(url: localAudioCacheURI!),
]);
}
void _loadFileAC() async {
final uri = await audioCache.load(kUrl2);
setState(() => localAudioCacheURI = uri.toString());
}
Widget localAsset() {
return SingleChildScrollView(
child: _Tab(
children: [
const Text("Play Local Asset 'audio.mp3':"),
_Btn(txt: 'Play', onPressed: () => audioCache.play('audio.mp3')),
const Text("Play Local Asset (via byte source) 'audio.mp3':"),
_Btn(
txt: 'Play',
onPressed: () async {
final bytes = await (await audioCache.loadAsFile('audio.mp3'))
.readAsBytes();
audioCache.playBytes(bytes);
},
),
const Text("Loop Local Asset 'audio.mp3':"),
_Btn(txt: 'Loop', onPressed: () => audioCache.loop('audio.mp3')),
const Text("Loop Local Asset (via byte source) 'audio.mp3':"),
_Btn(
txt: 'Loop',
onPressed: () async {
final bytes = await (await audioCache.loadAsFile('audio.mp3'))
.readAsBytes();
audioCache.playBytes(bytes, loop: true);
},
),
const Text("Play Local Asset 'audio2.mp3':"),
_Btn(txt: 'Play', onPressed: () => audioCache.play('audio2.mp3')),
const Text("Play Local Asset In Low Latency 'audio.mp3':"),
_Btn(
txt: 'Play',
onPressed: () {
audioCache.play('audio.mp3', mode: PlayerMode.LOW_LATENCY);
},
),
const Text(
"Play Local Asset Concurrently In Low Latency 'audio.mp3':",
),
_Btn(
txt: 'Play',
onPressed: () async {
await audioCache.play(
'audio.mp3',
mode: PlayerMode.LOW_LATENCY,
);
await audioCache.play(
'audio2.mp3',
mode: PlayerMode.LOW_LATENCY,
);
},
),
const Text("Play Local Asset In Low Latency 'audio2.mp3':"),
_Btn(
txt: 'Play',
onPressed: () {
audioCache.play('audio2.mp3', mode: PlayerMode.LOW_LATENCY);
},
),
getLocalFileDuration(),
],
),
);
}
Future<int> _getDuration() async {
final uri = await audioCache.load('audio2.mp3');
await advancedPlayer.setUrl(uri.toString());
return Future.delayed(
const Duration(seconds: 2),
() => advancedPlayer.getDuration(),
);
}
FutureBuilder<int> getLocalFileDuration() {
return FutureBuilder<int>(
future: _getDuration(),
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return const Text('No Connection...');
case ConnectionState.active:
case ConnectionState.waiting:
return const Text('Awaiting result...');
case ConnectionState.done:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
return Text(
'audio2.mp3 duration is: ${Duration(milliseconds: snapshot.data!)}',
);
default:
return Container();
}
},
);
}
Widget notification() {
return _Tab(
children: [
const Text("Play notification sound: 'messenger.mp3':"),
_Btn(
txt: 'Play',
onPressed: () =>
audioCache.play('messenger.mp3', isNotification: true),
),
],
);
}
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
StreamProvider<Duration>.value(
initialData: const Duration(),
value: advancedPlayer.onAudioPositionChanged,
),
],
child: DefaultTabController(
length: 5,
child: Scaffold(
appBar: AppBar(
bottom: const TabBar(
tabs: [
Tab(text: 'Remote Url'),
Tab(text: 'Local File'),
Tab(text: 'Local Asset'),
Tab(text: 'Notification'),
Tab(text: 'Advanced'),
],
),
title: const Text('audioplayers Example'),
),
body: TabBarView(
children: [
remoteUrl(),
localFile(),
localAsset(),
notification(),
Advanced(advancedPlayer: advancedPlayer),
],
),
),
),
);
}
}
class Advanced extends StatefulWidget {
final AudioPlayer advancedPlayer;
const Advanced({Key? key, required this.advancedPlayer}) : super(key: key);
@override
_AdvancedState createState() => _AdvancedState();
}
class _AdvancedState extends State<Advanced> {
bool? seekDone;
@override
void initState() {
widget.advancedPlayer.onSeekComplete
.listen((event) => setState(() => seekDone = true));
super.initState();
}
@override
Widget build(BuildContext context) {
final audioPosition = Provider.of<Duration>(context);
return SingleChildScrollView(
child: _Tab(
children: [
Column(
children: [
const Text('Source Url'),
Row(
children: [
_Btn(
txt: 'Audio 1',
onPressed: () => widget.advancedPlayer.setUrl(kUrl1),
),
_Btn(
txt: 'Audio 2',
onPressed: () => widget.advancedPlayer.setUrl(kUrl2),
),
_Btn(
txt: 'Stream',
onPressed: () => widget.advancedPlayer.setUrl(kUrl3),
),
],
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
),
],
),
Column(
children: [
const Text('Release Mode'),
Row(
children: [
_Btn(
txt: 'STOP',
onPressed: () =>
widget.advancedPlayer.setReleaseMode(ReleaseMode.STOP),
),
_Btn(
txt: 'LOOP',
onPressed: () =>
widget.advancedPlayer.setReleaseMode(ReleaseMode.LOOP),
),
_Btn(
txt: 'RELEASE',
onPressed: () => widget.advancedPlayer
.setReleaseMode(ReleaseMode.RELEASE),
),
],
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
),
],
),
Column(
children: [
const Text('Volume'),
Row(
children: [0.0, 0.3, 0.5, 1.0, 1.1, 2.0].map((e) {
return _Btn(
txt: e.toString(),
onPressed: () => widget.advancedPlayer.setVolume(e),
);
}).toList(),
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
),
],
),
Column(
children: [
const Text('Control'),
Row(
children: [
_Btn(
txt: 'resume',
onPressed: () => widget.advancedPlayer.resume(),
),
_Btn(
txt: 'pause',
onPressed: () => widget.advancedPlayer.pause(),
),
_Btn(
txt: 'stop',
onPressed: () => widget.advancedPlayer.stop(),
),
_Btn(
txt: 'release',
onPressed: () => widget.advancedPlayer.release(),
),
],
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
),
],
),
Column(
children: [
const Text('Seek in milliseconds'),
Row(
children: [
_Btn(
txt: '100ms',
onPressed: () {
widget.advancedPlayer.seek(
Duration(
milliseconds: audioPosition.inMilliseconds + 100,
),
);
setState(() => seekDone = false);
},
),
_Btn(
txt: '500ms',
onPressed: () {
widget.advancedPlayer.seek(
Duration(
milliseconds: audioPosition.inMilliseconds + 500,
),
);
setState(() => seekDone = false);
},
),
_Btn(
txt: '1s',
onPressed: () {
widget.advancedPlayer.seek(
Duration(seconds: audioPosition.inSeconds + 1),
);
setState(() => seekDone = false);
},
),
_Btn(
txt: '1.5s',
onPressed: () {
widget.advancedPlayer.seek(
Duration(
milliseconds: audioPosition.inMilliseconds + 1500,
),
);
setState(() => seekDone = false);
},
),
],
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
),
],
),
Column(
children: [
const Text('Rate'),
Row(
children: [0.5, 1.0, 1.5, 2.0, 5.0].map((e) {
return _Btn(
txt: e.toString(),
onPressed: () {
widget.advancedPlayer.setPlaybackRate(playbackRate: e);
},
);
}).toList(),
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
),
],
),
Text('Audio Position: $audioPosition'),
if (seekDone != null) Text(seekDone! ? 'Seek Done' : 'Seeking...'),
],
),
);
}
}
class _Tab extends StatelessWidget {
final List<Widget> children;
const _Tab({Key? key, required this.children}) : super(key: key);
@override
Widget build(BuildContext context) {
return Center(
child: Container(
alignment: Alignment.topCenter,
padding: const EdgeInsets.all(16.0),
child: SingleChildScrollView(
child: Column(
children: children
.map(
(w) => Container(
child: w,
padding: const EdgeInsets.all(6.0),
),
)
.toList(),
),
),
),
);
}
}
class _Btn extends StatelessWidget {
final String txt;
final VoidCallback onPressed;
const _Btn({Key? key, required this.txt, required this.onPressed})
: super(key: key);
@override
Widget build(BuildContext context) {
return ButtonTheme(
minWidth: 48.0,
child: ElevatedButton(child: Text(txt), onPressed: onPressed),
);
}
}