just_audio/lib/just_audio.dart

322 lines
11 KiB
Dart
Raw Normal View History

2019-11-25 14:50:21 +00:00
import 'dart:async';
2019-11-28 05:16:54 +00:00
import 'dart:io';
2019-11-25 14:50:21 +00:00
import 'package:flutter/services.dart';
2019-11-28 05:16:54 +00:00
import 'package:flutter/widgets.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:rxdart/rxdart.dart';
2019-11-25 14:50:21 +00:00
2019-11-28 05:16:54 +00:00
/// An object to manage playing audio from a URL, a locale file or an asset.
///
/// ```
/// final player = AudioPlayer();
/// await player.setUrl('https://foo.com/bar.mp3');
2019-11-30 15:52:54 +00:00
/// player.play();
2019-12-31 09:38:46 +00:00
/// player.pause();
/// player.play();
/// await player.stop();
/// await player.setClip(start: Duration(seconds: 10), end: Duration(seconds: 20));
/// await player.play();
2019-11-28 05:16:54 +00:00
/// await player.setUrl('https://foo.com/baz.mp3');
/// await player.seek(Duration(minutes: 5));
2019-11-30 15:52:54 +00:00
/// player.play();
2019-11-28 05:16:54 +00:00
/// await player.stop();
/// await player.dispose();
/// ```
///
/// You must call [dispose] to release the resources used by this player,
/// including any temporary files created to cache assets.
///
/// The [AudioPlayer] instance transitions through different states as follows:
///
/// * [AudioPlaybackState.none]: immediately after instantiation.
/// * [AudioPlaybackState.stopped]: eventually after [setUrl], [setFilePath] or
2019-12-27 05:43:09 +00:00
/// [setAsset] completes, and immediately after [stop].
2019-11-28 05:16:54 +00:00
/// * [AudioPlaybackState.paused]: after [pause] and after reaching the end of
/// the requested [play] segment.
/// * [AudioPlaybackState.playing]: after [play] and after sufficiently
/// buffering during normal playback.
/// * [AudioPlaybackState.buffering]: immediately after a seek request and
/// during normal playback when the next buffer is not ready to be played.
/// * [AudioPlaybackState.connecting]: immediately after [setUrl],
/// [setFilePath] and [setAsset] while waiting for the media to load.
2019-12-27 05:43:09 +00:00
/// * [AudioPlaybackState.completed]: immediately after playback reaches the
/// end of the media.
2019-11-30 15:52:54 +00:00
///
2019-11-28 05:16:54 +00:00
/// Additionally, after a [seek] request completes, the state will return to
/// whatever state the player was in prior to the seek request.
2019-11-25 14:50:21 +00:00
class AudioPlayer {
2019-11-30 15:52:54 +00:00
static final _mainChannel = MethodChannel('com.ryanheise.just_audio.methods');
2019-11-25 14:50:21 +00:00
static Future<MethodChannel> _init(int id) async {
await _mainChannel.invokeMethod('init', ['$id']);
2019-11-28 06:55:32 +00:00
return MethodChannel('com.ryanheise.just_audio.methods.$id');
2019-11-25 14:50:21 +00:00
}
2019-11-28 05:16:54 +00:00
final Future<MethodChannel> _channel;
final int _id;
Future<Duration> _durationFuture;
final _durationSubject = BehaviorSubject<Duration>();
AudioPlaybackEvent _audioPlaybackEvent;
2019-11-28 05:16:54 +00:00
Stream<AudioPlaybackEvent> _eventChannelStream;
2019-11-28 05:16:54 +00:00
StreamSubscription<AudioPlaybackEvent> _eventChannelStreamSubscription;
2019-11-28 05:16:54 +00:00
final _playbackEventSubject = BehaviorSubject<AudioPlaybackEvent>();
2019-11-28 05:16:54 +00:00
final _playbackStateSubject = BehaviorSubject<AudioPlaybackState>();
double _volume = 1.0;
double _speed = 1.0;
2019-11-28 05:16:54 +00:00
/// Creates an [AudioPlayer].
factory AudioPlayer() =>
AudioPlayer._internal(DateTime.now().microsecondsSinceEpoch);
AudioPlayer._internal(this._id) : _channel = _init(_id) {
2019-11-28 06:55:32 +00:00
_eventChannelStream = EventChannel('com.ryanheise.just_audio.events.$_id')
2019-11-28 05:16:54 +00:00
.receiveBroadcastStream()
.map((data) => _audioPlaybackEvent = AudioPlaybackEvent(
2019-11-28 05:16:54 +00:00
state: AudioPlaybackState.values[data[0]],
updatePosition: Duration(milliseconds: data[1]),
updateTime: Duration(milliseconds: data[2]),
speed: _speed,
2019-11-28 05:16:54 +00:00
));
_eventChannelStreamSubscription =
_eventChannelStream.listen(_playbackEventSubject.add);
2019-11-28 05:16:54 +00:00
_playbackStateSubject
.addStream(playbackEventStream.map((state) => state.state).distinct());
2019-11-28 05:16:54 +00:00
}
/// The duration of any media set via [setUrl], [setFilePath] or [setAsset],
/// or null otherwise.
Future<Duration> get durationFuture => _durationFuture;
/// The duration of any media set via [setUrl], [setFilePath] or [setAsset].
Stream<Duration> get durationStream => _durationSubject.stream;
/// The latest [AudioPlaybackEvent].
AudioPlaybackEvent get playbackEvent => _audioPlaybackEvent;
2019-11-28 05:16:54 +00:00
/// A stream of [AudioPlaybackEvent]s.
Stream<AudioPlaybackEvent> get playbackEventStream =>
_playbackEventSubject.stream;
2019-11-28 05:16:54 +00:00
/// The current [AudioPlaybackState].
AudioPlaybackState get playbackState => _audioPlaybackEvent.state;
/// A stream of [AudioPlaybackState]s.
2019-11-28 05:16:54 +00:00
Stream<AudioPlaybackState> get playbackStateStream =>
_playbackStateSubject.stream;
/// A stream periodically tracking the current position of this player.
Stream<Duration> getPositionStream(
[final Duration period = const Duration(milliseconds: 200)]) =>
Rx.combineLatest2<AudioPlaybackEvent, void, Duration>(
playbackEventStream,
// TODO: emit periodically only in playing state.
Stream.periodic(period),
2019-11-28 05:16:54 +00:00
(state, _) => state.position);
/// The current volume of the player.
double get volume => _volume;
/// The current speed of the player.
double get speed => _speed;
2019-12-27 05:43:09 +00:00
/// Loads audio media from a URL and returns the duration of that audio. It
/// is legal to invoke this method only from one of the following states:
///
/// * [AudioPlaybackState.none]
/// * [AudioPlaybackState.stopped]
/// * [AudioPlaybackState.completed]
2019-11-28 05:16:54 +00:00
Future<Duration> setUrl(final String url) async {
_durationFuture =
_invokeMethod('setUrl', [url]).then((ms) => Duration(milliseconds: ms));
final duration = await _durationFuture;
_durationSubject.add(duration);
return duration;
}
2019-12-27 05:43:09 +00:00
/// Loads audio media from a file and returns the duration of that audio. It
/// is legal to invoke this method only from one of the following states:
///
/// * [AudioPlaybackState.none]
/// * [AudioPlaybackState.stopped]
/// * [AudioPlaybackState.completed]
2019-11-30 15:52:54 +00:00
Future<Duration> setFilePath(final String filePath) =>
setUrl('file://$filePath');
2019-11-28 05:16:54 +00:00
/// Loads audio media from an asset and returns the duration of that audio.
2019-12-27 05:43:09 +00:00
/// It is legal to invoke this method only from one of the following states:
///
/// * [AudioPlaybackState.none]
/// * [AudioPlaybackState.stopped]
/// * [AudioPlaybackState.completed]
2019-11-28 05:16:54 +00:00
Future<Duration> setAsset(final String assetPath) async {
final file = await _cacheFile;
if (!file.existsSync()) {
await file.create(recursive: true);
}
2019-11-30 15:52:54 +00:00
await file
.writeAsBytes((await rootBundle.load(assetPath)).buffer.asUint8List());
2019-11-28 05:16:54 +00:00
return await setFilePath(file.path);
}
2019-11-30 15:52:54 +00:00
Future<File> get _cacheFile async => File(p.join(
(await getTemporaryDirectory()).path, 'just_audio_asset_cache', '$_id'));
2019-11-28 05:16:54 +00:00
2019-12-31 09:38:46 +00:00
/// Clip the audio to the given [start] and [end] timestamps.
Future<Duration> setClip({Duration start, Duration end}) async {
_durationFuture =
_invokeMethod('setClip', [start?.inMilliseconds, end?.inMilliseconds])
.then((ms) => Duration(milliseconds: ms));
final duration = await _durationFuture;
_durationSubject.add(duration);
return duration;
}
/// Plays the currently loaded media from the current position. The [Future]
/// returned by this method completes when playback completes or is paused or
/// stopped. It is legal to invoke this method only from one of the following
/// states:
2019-11-28 05:16:54 +00:00
///
/// * [AudioPlaybackState.stopped]
2019-12-27 05:43:09 +00:00
/// * [AudioPlaybackState.completed]
2019-11-28 05:16:54 +00:00
/// * [AudioPlaybackState.paused]
2019-12-31 09:38:46 +00:00
Future<void> play() async {
2019-11-28 05:16:54 +00:00
StreamSubscription subscription;
Completer completer = Completer();
2020-01-01 08:39:49 +00:00
bool startedPlaying = false;
subscription = playbackStateStream.listen((state) {
// TODO: It will be more reliable to let the platform
// side wait for completion since events on the flutter
// side can lag behind the platform side.
if (startedPlaying &&
(state == AudioPlaybackState.paused ||
state == AudioPlaybackState.stopped ||
state == AudioPlaybackState.completed)) {
subscription.cancel();
completer.complete();
} else if (state == AudioPlaybackState.playing) {
startedPlaying = true;
}
2019-11-28 05:16:54 +00:00
});
2019-12-31 09:38:46 +00:00
await _invokeMethod('play');
2019-11-28 05:16:54 +00:00
await completer.future;
}
/// Pauses the currently playing media. It is legal to invoke this method
/// only from the following states:
///
/// * [AudioPlaybackState.playing]
/// * [AudioPlaybackState.buffering]
Future<void> pause() async {
await _invokeMethod('pause');
}
/// Stops the currently playing media such that the next [play] invocation
/// will start from position 0. It is legal to invoke this method only from
/// the following states:
2019-11-28 05:16:54 +00:00
///
/// * [AudioPlaybackState.playing]
/// * [AudioPlaybackState.paused]
2019-11-28 05:16:54 +00:00
/// * [AudioPlaybackState.stopped]
2019-12-27 05:43:09 +00:00
/// * [AudioPlaybackState.completed]
2019-11-28 05:16:54 +00:00
Future<void> stop() async {
await _invokeMethod('stop');
}
/// Sets the volume of this player, where 1.0 is normal volume.
Future<void> setVolume(final double volume) async {
_volume = volume;
2019-11-28 05:16:54 +00:00
await _invokeMethod('setVolume', [volume]);
}
/// Sets the playback speed of this player, where 1.0 is normal speed.
Future<void> setSpeed(final double speed) async {
_speed = speed;
await _invokeMethod('setSpeed', [speed]);
}
2019-12-27 05:43:09 +00:00
/// Seeks to a particular position. It is legal to invoke this method from
/// any state except for [AudioPlaybackState.none] and
/// [AudioPlaybackState.connecting].
2019-11-28 05:16:54 +00:00
Future<void> seek(final Duration position) async {
await _invokeMethod('seek', [position.inMilliseconds]);
}
2019-12-27 05:43:09 +00:00
/// Release all resources associated with this player. You must invoke this
/// after you are done with the player. It is legal to invoke this method
/// only from the following states:
///
/// * [AudioPlaybackState.stopped]
/// * [AudioPlaybackState.completed]
/// * [AudioPlaybackState.none]
2019-11-28 05:16:54 +00:00
Future<void> dispose() async {
if ((await _cacheFile).existsSync()) {
(await _cacheFile).deleteSync();
}
await _invokeMethod('dispose');
await _durationSubject.close();
await _eventChannelStreamSubscription.cancel();
await _playbackEventSubject.close();
2019-11-28 05:16:54 +00:00
}
Future<dynamic> _invokeMethod(String method, [dynamic args]) async =>
(await _channel).invokeMethod(method, args);
}
/// Encapsulates the playback state and current position of the player.
class AudioPlaybackEvent {
2019-11-28 05:16:54 +00:00
/// The current playback state.
final AudioPlaybackState state;
2019-11-30 15:52:54 +00:00
2019-11-28 05:16:54 +00:00
/// When the last time a position discontinuity happened, as measured in time
/// since the epoch.
final Duration updateTime;
2019-11-30 15:52:54 +00:00
2019-11-28 05:16:54 +00:00
/// The position at [updateTime].
final Duration updatePosition;
/// The playback speed.
final double speed;
AudioPlaybackEvent({
2019-11-28 05:16:54 +00:00
@required this.state,
@required this.updateTime,
@required this.updatePosition,
@required this.speed,
2019-11-28 05:16:54 +00:00
});
/// The current position of the player.
Duration get position => state == AudioPlaybackState.playing
? updatePosition +
(Duration(milliseconds: DateTime.now().millisecondsSinceEpoch) -
updateTime) *
speed
2019-11-28 05:16:54 +00:00
: updatePosition;
@override
String toString() =>
"{state=$state, updateTime=$updateTime, updatePosition=$updatePosition, speed=$speed}";
2019-11-28 05:16:54 +00:00
}
/// Enumerates the different playback states of a player.
enum AudioPlaybackState {
none,
stopped,
paused,
playing,
buffering,
connecting,
2019-12-27 05:43:09 +00:00
completed,
2019-11-25 14:50:21 +00:00
}