flutter - 如何将数据发送到从 UI 扩展 BackgroundAudioTask 的 AudioServiceTask 类
问题描述
好吧,我被这个问题困住了。我有一个audioservice
( audioplayer.dart
) 的代码,它需要 aqueue
来玩。我正在playlist.dart
使用audioplayer.dart
并ModalRoute
保存在全局变量中的队列queue
。然后,我初始化 AudioPlayerService。现在到这里为止的一切都很好,但是在AudioPlayerTask
扩展的类中BackgroundAudioTask
,当我尝试访问变量(内部onStart
)时,它是一个空列表。我不知道问题出在哪里,而且我对这门课也不是很熟悉BackgroundAudioTask
。这是它的样子:
import .....
List<MediaItem> queue = [];
class TempScreen extends StatefulWidget {
@override
_TempScreenState createState() => _TempScreenState();
}
class _TempScreenState extends State<TempScreen> {
@override
Widget build(BuildContext context) {
queue = ModalRoute.of(context).settings.arguments;
// NOW HERE THE QUEUE IS FINE
return Container(.....all ui code);
}
// I'm using this button to start the service
audioPlayerButton() {
AudioService.start(
backgroundTaskEntrypoint: _audioPlayerTaskEntrypoint,
androidNotificationChannelName: 'Audio Service Demo',
androidNotificationColor: 0xFF2196f3,
androidNotificationIcon: 'mipmap/ic_launcher',
androidEnableQueue: true,
);
AudioService.updateQueue(queue);
print('updated queue at the start');
print('queue now is $queue');
AudioService.setRepeatMode(AudioServiceRepeatMode.none);
AudioService.setShuffleMode(AudioServiceShuffleMode.none);
AudioService.play();
}
}
void _audioPlayerTaskEntrypoint() async {
AudioServiceBackground.run(() => AudioPlayerTask());
}
class AudioPlayerTask extends BackgroundAudioTask {
AudioPlayer _player = AudioPlayer();
Seeker _seeker;
StreamSubscription<PlaybackEvent> _eventSubscription;
String kUrl = '';
String key = "38346591";
String decrypt = "";
String preferredQuality = '320';
int get index => _player.currentIndex == null ? 0 : _player.currentIndex;
MediaItem get mediaItem => index == null ? queue[0] : queue[index];
// This is just a function i'm using to get song URLs
fetchSongUrl(songId) async {
print('starting fetching url');
String songUrl =
"https://www.jiosaavn.com/api.php?app_version=5.18.3&api_version=4&readable_version=5.18.3&v=79&_format=json&__call=song.getDetails&pids=" +
songId;
var res = await get(songUrl, headers: {"Accept": "application/json"});
var resEdited = (res.body).split("-->");
var getMain = jsonDecode(resEdited[1]);
kUrl = await DesPlugin.decrypt(
key, getMain[songId]["more_info"]["encrypted_media_url"]);
kUrl = kUrl.replaceAll('96', '$preferredQuality');
print('fetched url');
return kUrl;
}
@override
Future<void> onStart(Map<String, dynamic> params) async {
print('inside onStart of audioPlayertask');
print('queue now is $queue');
// NOW HERE QUEUE COMES OUT TO BE AN EMPTY LIST
final session = await AudioSession.instance;
await session.configure(AudioSessionConfiguration.speech());
if (queue.length == 0) {
print('queue is found to be null.........');
}
_player.currentIndexStream.listen((index) {
if (index != null) AudioServiceBackground.setMediaItem(queue[index]);
});
// Propagate all events from the audio player to AudioService clients.
_eventSubscription = _player.playbackEventStream.listen((event) {
_broadcastState();
});
// Special processing for state transitions.
_player.processingStateStream.listen((state) {
switch (state) {
case ProcessingState.completed:
AudioService.currentMediaItem != queue.last
? AudioService.skipToNext()
: AudioService.stop();
break;
case ProcessingState.ready:
break;
default:
break;
}
});
// Load and broadcast the queue
print('queue is');
print(queue);
print('Index is $index');
print('MediaItem is');
print(queue[index]);
try {
if (queue[index].extras == null) {
queue[index] = queue[index].copyWith(extras: {
'URL': await fetchSongUrl(queue[index].id),
});
}
await AudioServiceBackground.setQueue(queue);
await _player.setUrl(queue[index].extras['URL']);
onPlay();
} catch (e) {
print("Error: $e");
onStop();
}
}
@override
Future<void> onSkipToQueueItem(String mediaId) async {
// Then default implementations of onSkipToNext and onSkipToPrevious will
// delegate to this method.
final newIndex = queue.indexWhere((item) => item.id == mediaId);
if (newIndex == -1) return;
_player.pause();
if (queue[newIndex].extras == null) {
queue[newIndex] = queue[newIndex].copyWith(extras: {
'URL': await fetchSongUrl(queue[newIndex].id),
});
await AudioServiceBackground.setQueue(queue);
// AudioService.updateQueue(queue);
}
await _player.setUrl(queue[newIndex].extras['URL']);
_player.play();
await AudioServiceBackground.setMediaItem(queue[newIndex]);
}
@override
Future<void> onUpdateQueue(List<MediaItem> queue) {
AudioServiceBackground.setQueue(queue = queue);
return super.onUpdateQueue(queue);
}
@override
Future<void> onPlay() => _player.play();
@override
Future<void> onPause() => _player.pause();
@override
Future<void> onSeekTo(Duration position) => _player.seek(position);
@override
Future<void> onFastForward() => _seekRelative(fastForwardInterval);
@override
Future<void> onRewind() => _seekRelative(-rewindInterval);
@override
Future<void> onSeekForward(bool begin) async => _seekContinuously(begin, 1);
@override
Future<void> onSeekBackward(bool begin) async => _seekContinuously(begin, -1);
@override
Future<void> onStop() async {
await _player.dispose();
_eventSubscription.cancel();
await _broadcastState();
// Shut down this task
await super.onStop();
}
Future<void> _seekRelative(Duration offset) async {
var newPosition = _player.position + offset;
// Make sure we don't jump out of bounds.
if (newPosition < Duration.zero) newPosition = Duration.zero;
if (newPosition > mediaItem.duration) newPosition = mediaItem.duration;
// Perform the jump via a seek.
await _player.seek(newPosition);
}
void _seekContinuously(bool begin, int direction) {
_seeker?.stop();
if (begin) {
_seeker = Seeker(_player, Duration(seconds: 10 * direction),
Duration(seconds: 1), mediaItem)
..start();
}
}
/// Broadcasts the current state to all clients.
Future<void> _broadcastState() async {
await AudioServiceBackground.setState(
controls: [
MediaControl.skipToPrevious,
if (_player.playing) MediaControl.pause else MediaControl.play,
MediaControl.stop,
MediaControl.skipToNext,
],
systemActions: [
MediaAction.seekTo,
MediaAction.seekForward,
MediaAction.seekBackward,
],
androidCompactActions: [0, 1, 3],
processingState: _getProcessingState(),
playing: _player.playing,
position: _player.position,
bufferedPosition: _player.bufferedPosition,
speed: _player.speed,
);
}
AudioProcessingState _getProcessingState() {
switch (_player.processingState) {
case ProcessingState.idle:
return AudioProcessingState.stopped;
case ProcessingState.loading:
return AudioProcessingState.connecting;
case ProcessingState.buffering:
return AudioProcessingState.buffering;
case ProcessingState.ready:
return AudioProcessingState.ready;
case ProcessingState.completed:
return AudioProcessingState.completed;
default:
throw Exception("Invalid state: ${_player.processingState}");
}
}
}
这是音频服务的完整代码,以防万一。
解决方案
(答案更新:从 v0.18 开始,这种陷阱不存在,因为 UI 和后台代码在共享隔离中运行。下面的答案仅与 v0.17 及更早版本相关。)
audio_serviceBackgroundAudioTask
在单独的隔离中运行您的。在 README 中,它是这样写的:
请注意,您的 UI 和后台任务在单独的隔离中运行,并且不共享内存。他们交流的唯一方式是通过消息传递。你的 Flutter UI 只会使用
AudioService
API 与后台任务进行通信,而你的后台任务只会使用AudioServiceBackground
API 与 UI 和其他客户端进行交互。
关键点是隔离不共享内存。如果在 UI 隔离中设置“全局”变量,则不会在后台隔离中设置它,因为后台隔离有自己单独的内存块。这就是为什么您的全局queue
变量为空的原因。它实际上不是同一个变量,因为现在您实际上有两个变量副本:一个在 UI 隔离中已设置值,另一个在后台隔离中尚未(尚未)设置值.
现在,您的后台隔离确实“稍后”将其自己的队列变量副本设置为某些东西,这通过消息传递 API 发生,您将队列从 UI 隔离传递到updateQueue
后台隔离接收该消息并将其存储到它的中的变量的自己的副本onUpdateQueue
。如果您在此之后打印出队列,它将不再为空。
onStart
您尝试设置队列的位置还有一行,尽管您可能应该删除该代码并让队列仅设置在onUpdateQueue
. 您不应该尝试访问队列,onStart
因为您的队列直到onUpdateQueue
. 如果您想在设置之前避免任何空指针异常,您可以将后台隔离中的队列初始化为一个空列表,它最终将被一个非空列表替换,onUpdateQueue
而不会为空。
我还建议您避免创建queue
全局变量。全局变量通常不好,但在这种情况下,它实际上可能会让您感到困惑,认为该队列变量在 UI 和后台隔离中是相同的,而实际上每个隔离都有自己的变量副本,可能不同价值观。因此,如果您制作两个单独的“本地”变量,您的代码会更清晰。一个在 UI 内部,一个在后台任务内部。
另一个建议是您应该注意消息传递 API 中的方法是异步方法。您应该等待音频服务启动,然后再向其发送消息,例如设置队列。并且在尝试从队列中播放之前,您应该等待队列设置:
await AudioService.start(....);
// Now the service has started, it is safe to send messages.
await AudioService.updateQueue(...);
// Now the queue has been updated, it is safe to play from it.
推荐阅读
- python - 如何将灰度图像转换为具有 x、y 和像素强度值的 csv 文件?
- java - 如何在 EditText 中更改图像大小?
- mapbox - 为什么 Geoserver 返回带有覆盖范围限制的 404 响应?
- angular - 如何自动更新自定义指令?
- php - 在没有太多流量的情况下创建 PHP API
- node.js - 节点环境抛出 UnhandledPromiseRejectionWarning
- php - 使用 try/catch 不会捕获异常
- groovy - Groovy 脚本
- ios - Apple iOS 生产证书 - [ KeyChain Group ]
- android - Kotlin onClick 清除字段