flutter sounds unable to play audio file - flutter

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');

Related

Flutter_sound doesn't work at the first time but after recording voice on iOS

I'm building a flutter app and inside I use flutter_sound for voice recording and playing.
It works totally fine with Android devices but not with iOS device.
Right after building the app, I play a sound fetched from firebase but there was no sound at all. However, after I record a new voice, the previously fetched sound can play properly.
This is the code for playing sound
void startPlay() {
isPlaying = true;
_player = FlutterSoundPlayer();
_player!.openPlayer();
_player!.startPlayer(
fromDataBuffer: widget.bodyBytes,
codec: Codec.pcm16,
sampleRate: 48000,
whenFinished: () {
isPlaying = false;
if(mounted) {
setState(() {});
}
});
setState(() {});
}
This is the code for recording
Future<bool> record() async {
var status = await Permission.microphone.request();
if (status != PermissionStatus.granted) {
status = await Permission.microphone.request();
return false;
}
recordingDataController = StreamController<Food>.broadcast();
// write to data
_sink = File(_tempFilePath!).openWrite();
recordingDataSubscriptor = recordingDataController!.stream.listen((buffer) {
if (buffer is FoodData) {
_sink.add(buffer.data!);
}
});
await _recorder!.openRecorder();
await _recorder!.startRecorder(
toStream: recordingDataController!.sink,
codec: Codec.pcm16,
numChannels: 1,
sampleRate: 48000,
);
return true;
}
Please help me, Love you all <3

Switching stream with Flutter WebRTC seems to fail

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'.

AssetsAudioPlayer the operation could not be completed iOS

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((){});
}

Barcode crash without errors

I am making an app using the qrCode scanner and when i open the app on my iphone and touch the button for the qrCode scanning it shuts down automatically , not opening even the camera.I used barcode_scan in pubspec.yaml and the code is:
String qrResult = "Not yet Scanned";
onPressed: () async {
String scaning = await BarcodeScanner.scan();
setState(() {
qrResult = scaning;
});
},
The app is made in flutter
Please You can use this package flutter_barcode_scanner 1.0.1 to make your Work Simple.Cheers!!
scan() async {
try {
dynamic bar = await BarcodeScanner.scan();
if(bar != null && bar.isNotEmpty){
print(" scanning qrcode ------------------------ $barcode");
setState(() {
barcode = bar;
});
}} on PlatformException catch (e) {
setState(() => this.barcode = '');
} on FormatException{
setState(() => this.barcode = '');
} catch (e) {
setState(() => this.barcode = '');
}
}

Unhandled Exception: setState() called after dispose() after backpress while downloading a file in flutter

I am using the dio plugin for downloading file in flutter and showing progress of download in widgets, while doing backpress from current downloading screen getting below exception
Unhandled Exception: setState() called after dispose(): _FileDownloadCardState#537ff(lifecycle state: defunct, not mounted)
This is my code with some file validation
Future<void> downloadFile(OfflineMapFile offlineMapFile) async {
if(offlineMapFile.isDownloading) {
return;
}
Directory fileDir;
try {
offlineMapFile.isDownloading = true;
Dio dio = Dio();
Directory dir = await UAAppContext.getInstance().appDir;
//todo: need to test on ios
fileDir = await new Directory(dir.path + offlineMapFile.fileStoragePath).create();
await dio.download(
offlineMapFile.fileUrl, "${fileDir.path}/${offlineMapFile.fileName}",
onReceiveProgress: (received, total) {
if (total != -1) {
print("Rec: $received , Total: $total");
debugPrint("Directory path : " +
offlineMapFile.fileStoragePath +
"/" +
offlineMapFile.fileName);
setState(() {
offlineMapFile.isDownloading = true;
offlineMapFile.isDownloaded = false;
downloadProgressString = ((received / total) * 100).toStringAsFixed(0) + "%";
});
}
});
} catch (e) {
print(e);
setState(() {
offlineMapFile.isDownloading = false;
offlineMapFile.isDownloaded = false;});
} finally {
// TODO Check whether the files are downloaded or not! Validation
// And set state accordingly.
setState(() {
//TODO change boolean as per the file Validation
offlineMapFile.isDownloading = false;
offlineMapFile.isDownloaded = true;
downloadProgressString = "Completed";
if(offlineMapFile.fileName.contains(".zip") && fileDir != null){
CommonUtils.unzipFile(fileDir.path +"/"+ offlineMapFile.fileName, fileDir.path + "/Offline/");
}
});
print("Download completed");
}
}
You are calling a setState on a unmounted widget, to solve this you just need to add this condition
if(mounted) {
setState(//....
}