I am using this package: https://pub.dev/packages/audioplayers
I have 2 problems, first of all the way the code is, when I press play the music starts, but when I press stop it does nothing, it is as if I were emitting a state that does not hit the same audioPlayer. Second, I don't know how I could change the PlayerState, the player state in the pad comes out as null, and I think that I am emitting these states wrong, could someone please show me in a practical way which is the correct way so I learn it? since I am relatively new to flutter_bloc.
Bloc
import 'dart:async';
import 'package:audioplayers/audioplayers.dart';
import 'package:bloc/bloc.dart';
import 'package:meta/meta.dart';
part 'audioplayersbloc_event.dart';
part 'audioplayersbloc_state.dart';
class AudioPlayersBloc
extends Bloc<AudioPlayersBlocEvent, AudioPlayersBlocState> {
AudioPlayersBloc() : super(AudioPlayersBlocState());
String URL =
'******'; // i put "***" because private url but its a mp3 file
@override
Stream<AudioPlayersBlocState> mapEventToState(
AudioPlayersBlocEvent event,
) async* {
if (event is OnPlayPlayerRemote) {
PlayerState plyState;
audioPlayersBloc.state.audioPlayer.onPlayerStateChanged.listen((event)
{
plyState = event;
});
yield this.state.copyWith(audioPlayer: await this.playMusic(),
playerState: plyState);
} else if (event is OnStopPlayer) {
await this.stopMusic();
yield this.state.copyWith(audioPlayer: await this.stopMusic());
}
}
playMusic() async {
await this.state.audioPlayer.play(URL);
}
pauseMusic() async {
await this.state.audioPlayer.pause();
}
stopMusic() async {
await this.state.audioPlayer.stop();
}
}
State
part of 'audioplayersbloc_bloc.dart';
class AudioPlayersBlocState {
final AudioPlayer audioPlayer = AudioPlayer();
final PlayerState playerState = PlayerState.PAUSED;
final AudioCache audioCache = AudioCache();
AudioPlayersBlocState(
{AudioPlayer? audioPlayer,
PlayerState? playerState,
AudioCache? audioCache});
AudioPlayersBlocState copyWith(
{AudioPlayer? audioPlayer,
PlayerState? playerState,
AudioCache? audioCache}) =>
AudioPlayersBlocState(
audioPlayer: audioPlayer ?? this.audioPlayer,
playerState: playerState ?? this.playerState,
audioCache: audioCache ?? this.audioCache);
}
Event
part of 'audioplayersbloc_bloc.dart';
@immutable
abstract class AudioPlayersBlocEvent {}
class OnPlayPlayerRemote extends AudioPlayersBlocEvent {}
class OnStopPlayer extends AudioPlayersBlocEvent {}
The button where i play the music in the home page, is only a button, it is a simple player
IconButton(
icon: Icon(Icons.play_arrow),
onPressed: () {
context.read<AudioPlayersBloc>().add(OnPlayPlayerRemote());
},
),
IconButton(
icon: Icon(Icons.stop),
onPressed: () {
context.read<AudioPlayersBloc>().add(OnStopPlayer());
},
),