Music player playing two songs - flutter

I need to play the song after killing the app. songs are playing after killing them but now when I reopen the app it plays 2 songs at the same time is there any way to play a song from the same position and only one song play?
dependency= assets_audio_player
#override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
switch (state) {
case AppLifecycleState.paused:
_state == AppLifecycleState;
break;
case AppLifecycleState.resumed:
_state == AppLifecycleState;
break;
case AppLifecycleState.inactive:
_state == AppLifecycleState;
break;
case AppLifecycleState.detached:
_state == AppLifecycleState;
break;
default:
}
if (_state == AppLifecycleState.detached) {
return null;
} else {
if (audioplayer.playerState.value == 'PlayerState.play') {
return null;
} else {
print('------------------state of player ${audioplayer.playerState.value}');
return setupPlaylist();
}
}
}

Related

Want to post geolocation on a external api using getx

I have already got the geolocation with longitude and latitude using the geolocation plugin with getx but now I want to post the same longitude and latitude on API with already present in the backhand the model is yet to be created and even the provider is also yet to be done and I don't know how and the location API post should run in the background once with the application opens up.
API body:-
{
"longitude":"55.5852",
"latitude":"77.6532"
}
Controller code:-
class RootController extends GetxController {
var latitude = 'Getting Latitude..'.obs;
var longitude = 'Getting Longitude..'.obs;
var address = 'Getting Address..'.obs;
final currentIndex = 0.obs;
final notificationsCount = 0.obs;
final customPages = <CustomPage>[].obs;
NotificationRepository _notificationRepository;
CustomPageRepository _customPageRepository;
StreamSubscription<Position> streamSubscription;
RootController() {
_notificationRepository = new NotificationRepository();
_customPageRepository = new CustomPageRepository();
}
#override
void onInit() async {
await getCustomPages();
getNotificationsCount();
if (Get.arguments != null && Get.arguments is int) {
changePageInRoot(Get.arguments as int);
} else {
changePageInRoot(0);
}
super.onInit();
getLocation();
}
#override
void onReady(){
super.onReady();
}
#override
void onClose(){
streamSubscription.cancel();
}
getLocation() async{
bool serviceEnabled;
LocationPermission permission;
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if(!serviceEnabled){
await Geolocator.openLocationSettings();
return Future.error('Location Services are disabled.');
}
permission = await Geolocator.checkPermission();
if(permission == LocationPermission.denied){
permission = await Geolocator.requestPermission();
if(permission == LocationPermission.denied){
return Future.error('Location permissions are denied');
}
}
if (permission == LocationPermission.deniedForever){
return Future.error('Location permissions are permanently denied');
}
streamSubscription = Geolocator.getPositionStream().listen((Position position) {
latitude.value = 'Latitude:${position.latitude}';
longitude.value = 'Longitude:${position.latitude}';
getAddressFromLatLang(position);
print(latitude.value);
print(longitude.value);
});
}
Future<void> getAddressFromLatLang(Position position)async{
List<Placemark> placemark = await
placemarkFromCoordinates(position.latitude,position.longitude);
Placemark place = placemark[0];
address.value = 'address:${place.locality},${place.country}';
}
List<Widget> pages = [
HomeView(),
// EServicesView2(),
ReviewsView(),
MessagesView(),
AccountView(),
];
Widget get currentPage => pages[currentIndex.value];
/**
* change page in route
* */
void changePageInRoot(int _index) {
currentIndex.value = _index;
}
void changePageOutRoot(int _index) {
currentIndex.value = _index;
Get.offNamedUntil(Routes.ROOT, (Route route) {
if (route.settings.name == Routes.ROOT) {
return true;
}
return false;
}, arguments: _index);
}
Future<void> changePage(int _index) async {
if (Get.currentRoute == Routes.ROOT) {
changePageInRoot(_index);
} else {
changePageOutRoot(_index);
}
await refreshPage(_index);
}
Future<void> refreshPage(int _index) async {
switch (_index) {
case 0:
{
await Get.find<HomeController>().refreshHome();
break;
}
case 2:
{
await Get.find<MessagesController>().refreshMessages();
break;
}
}
}
void getNotificationsCount() async {
notificationsCount.value = await _notificationRepository.getCount();
}
Future<void> getCustomPages() async {
customPages.assignAll(await _customPageRepository.all());
}
}
what else should I do?

i cannot stop/pause a song in audioplayers

I am using the audioplayers plugin in my code.
I can play audio but I cannot stop/pause audio. Following is a function that I use to play/stop the audio.
Future<void> onPlay({#required filepath, #required index}) async {
AudioPlayer audioPlayer = AudioPlayer(mode: PlayerMode.MEDIA_PLAYER);
if (!_isPlaying) {
int result = await audioPlayer.play(filepath, isLocal: true);
if (result == 1) {
setState(() {
_isPlaying = true;
_selectedIndex = index;
});
}
} else {
int result = await audioPlayer.stop();
if (result == 1) {
setState(() {
_isPlaying = false;
});
}
}
}
}
You're instantiating a new AudioPlayer audioPlayer object each time you call onPlay, which leaves you unable to stop that same player later.
Store your AudioPlayer audioPlayer in the state somewhere.
AudioPlayer audioPlayer = AudioPlayer(mode: PlayerMode.MEDIA_PLAYER);
Future<void> onPlay({#required filepath, #required index}) async {
if (!_isPlaying) {
int result = await audioPlayer.play(filepath, isLocal: true);
if (result == 1) {
setState(() {
_isPlaying = true;
_selectedIndex = index;
});
}
} else {
int result = await audioPlayer.stop();
if (result == 1) {
setState(() {
_isPlaying = false;
});
}
}
}

flutter audio manager onEvents not working

I am using AudioManager and I am going to check audio status (start, ready, play, pause, volume and so on). Sometimes onEvents function doesn't work.
AudioManager audioManager = AudioManager.instance;
bool _isLoading;
try {
_isLoading = true;
String result = await audioManager.startInfo(audio, auto: true);
print("start result $result");
audioManager.nextMode(playMode: PlayMode.single);
} catch (e) {
print(e);
}
audioManager.onEvents((events, args) {
print("$events, $args");
switch (events) {
case AudioManagerEvents.start:
_isLoading = true;
break;
case AudioManagerEvents.ready:
_isLoading = false;
break;
case AudioManagerEvents.seekComplete:
print("seek completed");
break;
case AudioManagerEvents.buffering:
_isLoading = false;
break;
case AudioManagerEvents.playstatus:
_isLoading = false;
break;
case AudioManagerEvents.timeupdate:
_isLoading = false;
audioManager.updateLrc(args["position"].toString());
break;
case AudioManagerEvents.error:
_isLoading = false;
break;
case AudioManagerEvents.ended:
audioManager.next();
break;
case AudioManagerEvents.volumeChange:
_volume = audioManager.volume;
break;
default:
_isLoading = false;
break;
}
setState(() {});
});
_isLoading is always true even if audio is playing now.

Flutter: Check Internet connectivity and navigate based on output?

I am new to flutter, I want to check whether the internet is available or not and based on the condition, the screen has to change. I have written the code below (screen switch is working properly), but I am not able to get bool output(internet). When I removed the Future in check internet class, it throws an error. Can you please solve the issue:
class _ScreenState extends State<ChannelScreen> {
bool isInternet;
bool result;
#override
void initState() {
// TODO: implement initState
result = check();
super.initState();
}
#override
Widget _buildChild() {
print ("The output “);
print (result);
if (result != Null && result == true) {
// if internet is ON
return Container();
}
//if internet is off
return Container();
}
Widget build(BuildContext context) {
return new Container(child: _buildChild());
}
}
Future<bool> check() async{
var connectivityResult = await Connectivity().checkConnectivity();
if (connectivityResult == ConnectivityResult.mobile) {
print ("******* Mobile is ON ******");
return true;
} else if (connectivityResult == ConnectivityResult.wifi) {
print ("******* Wifi is ON ******");
return true;
}
print ("No connectivity");
return false;
}
You can use StreamBuilder
StreamBuilder(
stream: Connectivity().onConnectivityChanged,
builder: (context, snapshot) {
// Use this to avoid null exception
if (snapshot.connectionState == ConnectionState.none) {
return CircularProgressIndicator();
} else {
ConnectivityResult result = snapshot.data;
// Check Connectivity result here and display your widgets
if(ConnectivityResult.none) {
yourWidgetForNoInternet();
} else {
yourWidgetForInternet();
}
}
},
)
bool hasInternet = false, isChecking = true;
#override
void initState() {
super.initState();
check();
}
#override
Widget build(BuildContext context) {
return Container(
child: isChecking
? ListTile(
leading: CircularProgressIndicator(), title: Text('Checking...'))
: hasInternet
? ListTile(title: Text('Your widget here...'))
: ListTile(
leading: Icon(Icons.info),
title: Text('No Internet Conncetion')));
}
check() async {
var connectivityResult = await Connectivity().checkConnectivity();
if (connectivityResult == ConnectivityResult.mobile) {
print("******* Mobile is ON ******");
setState(() {
isChecking = false;
hasInternet = true;
//navigate to another screen.....
});
} else if (connectivityResult == ConnectivityResult.wifi) {
print("******* Wifi is ON ******");
setState(() {
isChecking = false;
hasInternet = true;
//navigate to another screen.....
});
} else {
setState(() {
isChecking = false;
hasInternet = false;
});
}
}
There is a plugin to use connectivity:
https://pub.dev/packages/connectivity#-readme-tab-
I use following code to check whether the internet is connected or not
static Future<bool> checkInternetConnectivity() async {
bool isConnected;
try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
isConnected = true;
}
} on SocketException catch (_) {
isConnected = false;
}
return isConnected;
}

Set gain and expsoure without DisplayPropertyPage (Aforge, Directshow)

can anyone tell me how I can change gain or exposure with directshow from Afroge.
I already tried what you can see below but didn't succeed. What am I doing wrong?
Thanks in advance
using AForge.Video;
using AForge.Video.DirectShow;
...
...
VideoCaptureDevice videoSource;
private void changeProp(int value)
{
videoSource.SetCameraProperty(CameraControlProperty.Exposure, value, CameraControlFlags.Auto);
}
This code works for me. Most of the code taken from Afroge Samples.
private VideoCaptureDevice videoDevice;
private FilterInfoCollection videoDevices;
private VideoCapabilities[] videoCapabilities;
public Bool SetCamera(Cameras camera, int camDevice, CameraResolution camResolution,
int exposureValue, int zoomValue, int focusValue)
{
// Enumerate video devices
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
//Select camera according to specified index
videoDevice = new VideoCaptureDevice(videoDevices[camDevice].MonikerString);
//Get video capabilities for setting the resoluton
videoCapabilities = videoDevice.VideoCapabilities;
if (camera == Cameras.C910)
{
switch (camResolution)
{
case CameraResolution.A_640x480:
videoDevice.VideoResolution = videoCapabilities[0];
break;
case CameraResolution.B_800x600:
videoDevice.VideoResolution = videoCapabilities[14];
break;
case CameraResolution.C_960x720:
videoDevice.VideoResolution = videoCapabilities[16];
break;
case CameraResolution.D_1280x720:
videoDevice.VideoResolution = videoCapabilities[17];
break;
case CameraResolution.E_1920x1080:
videoDevice.VideoResolution = videoCapabilities[24];
break;
default:
videoDevice.VideoResolution = videoCapabilities[0];
break;
}
}
else if (camera == Cameras.C920)
{
switch (camResolution)
{
case CameraResolution.A_640x480:
videoDevice.VideoResolution = videoCapabilities[0];
break;
case CameraResolution.B_800x600:
videoDevice.VideoResolution = videoCapabilities[10];
break;
case CameraResolution.C_960x720:
videoDevice.VideoResolution = videoCapabilities[12];
break;
case CameraResolution.D_1280x720:
videoDevice.VideoResolution = videoCapabilities[14];
break;
case CameraResolution.E_1920x1080:
videoDevice.VideoResolution = videoCapabilities[16];
break;
default:
videoDevice.VideoResolution = videoCapabilities[0];
break;
}
}
else
{
videoDevice.VideoResolution = videoCapabilities[0];
}
try
{
videoDevice.SetCameraProperty(
CameraControlProperty.Zoom,
zoomValue,
CameraControlFlags.Manual);
videoDevice.SetCameraProperty(
CameraControlProperty.Focus,
focusValue,
CameraControlFlags.Manual);
videoDevice.SetCameraProperty(
CameraControlProperty.Exposure,
exposureValue,
CameraControlFlags.Manual);
}
catch (Exception ex)
{
MessageBox.show(ex.ToString());
}