I'm trying to switch from the front to back camera using Flutter WebRTC but cannot get it working.
I have the following
// Stop the current stream and remove the tracks
await Future.forEach(videoStream!.getVideoTracks(), (MediaStreamTrack? track) async {
if (track != null) {
try {
await track.stop();
await videoStream!.removeTrack(track);
} catch (e) {
if (kDebugMode) {
print(e);
}
}
}
});
videoStream!.getVideoTracks().forEach((track) {
track.stop();
videoStream!.removeTrack(track, removeFromNative: true);
});
final mediaConstraints = {
'audio': false, // NO need to capture audio again
'video': {
'deviceId': videoInputDeviceId,
}
};
MediaStream newStream = await navigator.mediaDevices.getUserMedia(mediaConstraints);
final newTrack = newStream.getVideoTracks()[0];
await videoStream!.addTrack(newTrack, addToNative: true);
Getting the following errors if I place try catch around them
flutter: PlatformException(mediaStreamRemoveTrack: Track is nil, null, null, null)
flutter: !--- Event: Failed to enable webcam
flutter: Concurrent modification during iteration: Instance(length:0) of '_GrowableList'.
Related
I have used flutter_barcode_scanner: ^2.0.0 package to scan barcodes it work fine but I scan continuously and after few barcodes i want to close the camera and return back to screen now I am stock so how the camera is closed after scanning few barcodes.
the following is a scenario I wont to implement
scanBarcode() {
FlutterBarcodeScanner.getBarcodeStreamReceiver(
"#ff6666",
"Cancel",
false,
ScanMode.DEFAULT,
)!
.listen(
(barcode) {
setState(() {
list.add(barcode);
});
if (list.length == 10) {
// I want to close camera here and show page again?
}
},
);
}
I had the same issue. The workaround is to loop on single scan. So as a result you can still continue to use flutter_barcode_scanner package :).
In my case i don't need to call setState or something like to update the UI but you can do it if you need.
Future<String?> _scanBarcodeNormal() async {
String? barcodeScanRes;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
barcodeScanRes = await FlutterBarcodeScanner.scanBarcode('#ff6666', 'Cancel', true, ScanMode.BARCODE);
} on PlatformException {
barcodeScanRes = 'Failed to get platform version.';
}
return barcodeScanRes;
}
void _scanBarCodeListAndFetchData() async{
String? barcode = await _scanBarcodeNormal();
final List<String> barcodeList = [];
// continue scanning
while(barcode != null){
if(barcode == "-1"){ // cancel button -> -1
barcode = null;
}
// add the barcode
else {
// avoid duplicates
if(!barcodeList.contains(barcode)){
barcodeList.add(barcode);
}
// you can also call setState(() {....} here
if (barcodeList.length == 10) {
barcode = null; // out !
}
else{ // next scan
barcode = await _scanBarcodeNormal();
}
}
}
if(barcodeList.isEmpty) {
UiUtils.showToast(message: "No barcode scanned, abort", toastLength: Toast.LENGTH_SHORT);
}
else{
UiUtils.showToast(message: "${barcodeList.length} barcodes scanned", toastLength: Toast.LENGTH_SHORT);
// your work
}
}
I have integrated firebase dynamic links with my app. It works fine with foreground and background states. However, the app crashes when I open it on terminated state. Here is my code to handle dynamic links
static Future<void> initDynamicLinks() async {
try {
// terminated state
final PendingDynamicLinkData initLink =
await FirebaseDynamicLinks.instance.getInitialLink();
if (initLink != null) {
print('init link $initLink');
final Uri deeplink = initLink?.link;
if (deeplink != null) {
print('routing');
// routing(deeplink, deeplink.queryParameters);
} else {
print('deep link is null');
}
} else {
print('init link is null');
}
} catch (e) {
print('error getting link $e');
}
// background and foreground states
FirebaseDynamicLinks.instance.onLink.listen((dynamicLinkData) async {
final Uri deeplink = dynamicLinkData.link;
final queryParams = deeplink.queryParameters;
if (deeplink != null) {
routing(deeplink, queryParams);
} else {
print('listen link is null');
}
}).onError((error) {
print('onLink error');
print(error.message);
});
}
The dynamic link gets printed and it is not null, but what I get is a blank screen, half of it black and the other half is red.
Note: routing is a function that navigates to a specific path.
Any idea what might be the issue?
I'm using Flutter Sound Recorder as recorder for my audio files and I'm trying to open the audio file with AssetsAudioPlayer but I'm getting this error:
url: file:///var/mobile/Containers/Data/Application/10E4FD0F-E4F2-491E-A1A0-360A3E294217/Library/Caches/audios/1656038702016.wav
"playback failed"
2022-06-23 23:45:04.546002-0300 Runner[412:13249] flutter: PlatformException(PLAY_ERROR, Cannot play /var/mobile/Containers/Data/Application/10E4FD0F-E4F2-491E-A1A0-360A3E294217/Library/Caches/audios/1656038702016.wav, The operation could not be completed, null)
2022-06-23 23:45:04.546905-0300 Runner[412:13249] [VERBOSE-2:ui_dart_state.cc(198)] Unhandled Exception: PlatformException(PLAY_ERROR, Cannot play /var/mobile/Containers/Data/Application/10E4FD0F-E4F2-491E-A1A0-360A3E294217/Library/Caches/audios/1656038702016.wav, The operation could not be completed, null)
I've tried to use Audio Players but I got an error too
"iOS => call setVolume, playerId 57c0b5cc-3c75-4f8f-bf99-ad8ddbcb7709"
"iOS => call setUrl, playerId 57c0b5cc-3c75-4f8f-bf99-ad8ddbcb7709"
""
2022-06-23 18:27:00.168194-0300 Runner[16264:695114] flutter: AVPlayerItem.Status.failed
Any idea of what can I Do?
My recording settings:
Future<void> _onRecordButtonPressed() async {
if(_isRecording){
await _myRecorder?.stopRecorder();
_isRecording = false;
_isRecorded = true;
}else{
_isRecorded = false;
_isRecording = true;
await _startRecording();
}
setState((){
});
}
My AssetsAudioPlayer settings:
_onPlayButtonPressed() async {
if(!_isPlaying) {
_isPlaying = true;
await audioPlayer2.onPlayerError.listen((event) {
print(event);
});
await _assetsAudioPlayer.open(Audio.file(FilePathAndroidBitmap));
}else{
audioPlayer2.pause();
_isPlaying = false;
}
setState((){});
}
I want to upload an image to server
I'm using the Image Picker plugin to pick image
this code work without any exception on samsung tab
but Catch error on xiaomi phone.
the onImageButtonPressed run in all devices.
Future<void> onImageButtonPressed({
BuildContext? context,
}) async {
try {
final XFile? pickedFile =
await picker.pickImage(source: ImageSource.camera);
if (pickedFile != null) {
imageFileList!.add(pickedFile);
logger.i('done , image picked');
File image = File(pickedFile.path);
logger.i(image); // on xiaomi and samsung log the same result "File: '/data/user/0/com.grand.technology.driver/cache/8227d4f4-df70-441d-9677-b95b64b1bf323122241454085685040.jpg'"
await uploadOrderPic(order.id.toString(), image);
}
update();
} catch (e) {
pickImageError = e;
logger.e(e);
update();
}
}
but the exception happen here
uploadOrderPic(String id, File image) async {
uploading.value = true;
var response = await OrderApi()
.uploadOrderPic(orderID: id, image: image)
.then((value) {
logger.i(value.data); //samsung tab log Instance of 'UploadedImage' but xiaomi phone catch error
uploading.value = false;
var uploadedImage = (value.data) as UploadedImage;
imageURLsList.add(uploadedImage.url!);
}).catchError((error) {
Get.snackbar('Failed', 'Uploading Image Failed',
backgroundColor: redColor);
logger.e(error); // type 'Null' is not a subtype of type 'UploadedImage' in type cast
});
try {
} on TimeoutException {
Get.snackbar(
'Connection Error', 'Check Your Internet Connection Please!');
} catch (e) {
logger.e(e);
}
}
this code upload image to server
Future<ApiResponse> uploadOrderPic(
{required String orderID,
required File image}) async {
ApiResponse apiResponse = ApiResponse();
var token = await getToken();
try {
var request = http.MultipartRequest("POST", Uri.parse(uploadPicUrl));
request.files.add(await http.MultipartFile.fromPath('image', image.path));
request.fields['id'] = orderID;
request.headers[HttpHeaders.authorizationHeader] = 'Bearer $token';
var response =
await request.send().then((value) => http.Response.fromStream(value));
apiResponse.data =
UploadedImage.fromJson(jsonDecode(response.body)['data']);
} catch (e) {
logger.e(e);
apiResponse.error = serverError;
}
return apiResponse;
}
I am using flutter_sounds package to play audio file.
My audio file exists and is valid file.
For some unknown reason below code is not working and unable to play the audio.
FlutterSoundPlayer _mPlayer = FlutterSoundPlayer();
try {
var t = await _mPlayer.openAudioSession();
print('after open');
print('_mPlayerIsInited');
setState(() async {
_isPlayerToucher = true;
_mPlayerIsInited = true;
_mPlayerisPaused = false;
});
} catch (e) {
print('ERROR');
print(e.toString());
}
await _mPlayer.startPlayer(
fromURI: widget.content,
whenFinished: () async {
await _mPlayer.stopPlayer();
_mPlayer.closeAudioSession();
setState(() {
_mPlayerIsInited = false;
});
});
I am unable to see the print 'after open'
i see below in console.
I/flutter ( 7834): FS:---> openAudioSession
I recommend you to use another package audioplayers
AudioCache _audioCache;
_audioCache = AudioCache(
prefix: "audio/",
fixedPlayer: AudioPlayer()..setReleaseMode(ReleaseMode.STOP));
_audioCache.play('open-up.mp3');