How to play google drive's mp3 file in Flutter - flutter

I have uploaded some mp3 files to my google drive. And now I want to play those mp3 files in my flutter app using audioplayers package.
https://drive.google.com/file/d/1v8RBvEOpsEDlD_o7OA2TKgxysF-O5jUW/view?usp=sharing. This is my public shareable link of my mp3 on google drive.
void getAudio() async {
var url =
"https://drive.google.com/file/d/1v8RBvEOpsEDlD_o7OA2TKgxysF-O5jUW/view?usp=sharing";
if (isPlaying) {
var res = await audioPlayer.pause();
if (res == 1) {
print("isPlaying $res");
setState(() {
isPlaying = false;
});
}
} else {
var res = await audioPlayer.play(url, isLocal: false);
print("!isPlaying $res");
if (res == 1) {
setState(() {
isPlaying = true;
});
}
}
audioPlayer.onDurationChanged.listen((Duration d) {
setState(() {
duration = d;
});
});
audioPlayer.onAudioPositionChanged.listen((Duration d) {
setState(() {
position = d;
});
});
}

you have to try direct url for your file like this
https://drive.google.com/uc?export=download&confirm=no_antivirus&id=1v8RBvEOpsEDlD_o7OA2TKgxysF-O5jUW

Related

Save images in a custom folder in the gallery

Im new at Flutter and im trying to add images taken in my app to a custom folder in the gallery. Its the same as on WhatsApp, if you take a picture in a chat the WhatsApp create a custom folder called WhatsApp Images.
For that, I tried this:
Future<bool> saveFile(String url, String fileName) async {
Directory directory;
try {
if (Platform.isAndroid) {
if (await _requestPermission(Permission.storage)) {
directory = (await getExternalStorageDirectory())!;
String newPath = '';
List<String> folders = directory.path.split('/');
for (int x = 1; x < folders.length; x++) {
String folder = folders[x];
if (folder != 'Android') {
newPath += '/$folder';
} else {
break;
}
}
newPath = '$newPath/OnlaineApp';
directory = Directory(newPath);
} else {
return false;
}
} else {
if (await _requestPermission(Permission.photos)) {
directory = await getTemporaryDirectory();
} else {
return false;
}
}
if (!await directory.exists()) {
await directory.create(recursive: true);
}
if (await directory.exists()) {
File saveFile = File('${directory.path}/$fileName');
await dio.download(url, saveFile.path,
onReceiveProgress: (downloaded, totalSize) {
setState(() {
progress = downloaded / totalSize;
});
});
if (Platform.isIOS) {
await ImageGallerySaver.saveFile(
saveFile.path,
isReturnPathOfIOS: true,
);
}
return true;
}
} catch (e) {
print(e);
}
return false;
}
Future<bool> _requestPermission(Permission permission) async {
if (await permission.isGranted) {
return true;
} else {
var result = await permission.request();
if (result == PermissionStatus.granted) {
return true;
} else {
return false;
}
}
}
downloadFile() async {
setState(() {
loading = true;
});
bool downloaded = await saveFile(
'lib/assets/images/fundo_interno.png',
'OnlaineApp Imagens',
);
if (downloaded) {
print('File downloaded');
} else {
print('Problem downloaded file');
}
setState(() {
loading = false;
});
}
I already add in Android>app>src>main> AndroidManifest.xml these lines of code (for permission):
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
...
android:requestLegacyExternalStorage="true"
The problem I got is: I/flutter ( 5424): FileSystemException: Creation failed, path = '/storage/emulated/0/OnlaineApp' (OS Error: Permission denied, errno = 13)

How to Read a docx file text from google drive?

Future<void> _loadFileContent() async {
final file = File(widget.filePath);
final extension = file.path.split('.').last.toLowerCase();
if (extension == 'pdf') {
final pdf = await PDFDoc.fromFile(file);
final pages = await pdf.pages;
final texts = await Future.wait(pages.map((page) => page.text));
_fileContent = texts.join('\n');
} else if (extension == 'txt') {
_fileContent = await file.readAsString();
// var decoded = base64.decode( _fileContent);
} else if (extension == 'docx') {
} else {
throw Exception('Unsupported file extension: $extension');
}
setState(() {
_isLoading = false;
});
How to Read a docx file text from google drive? How to implement with use of libary any suggection

flutter google_speach response stream not working

final serviceAccount = ServiceAccount.fromString(r'''{
Json private keys
}''');
final speechToText = SpeechToText.viaServiceAccount(serviceAccount);
final config = RecognitionConfig(
encoding: AudioEncoding.LINEAR16,
model: RecognitionModel.basic,
enableAutomaticPunctuation: true,
sampleRateHertz: 16000,
languageCode: 'en-US');
final streamingConfig =
StreamingRecognitionConfig(config: config, interimResults: true);
Stream<List<int>> stream =
(await MicStream.microphone(sampleRate: 16000)) as Stream<List<int>>;
final responseStream =
speechToText.streamingRecognize(streamingConfig, stream);
if (_isListining) {
setState(() {
_isListining = false;
});
} else {
setState(() {
_isListining = true;
print('hello');
try {
responseStream.listen((data) {
print(data.results.length);
setState(() {
_sendController.text = data.results
.map((e) => e.alternatives.first.transcript)
.join('/n');
});
print(content);
}, onDone: () {
setState(() {
setState(() {
_isListining = false;
});
});
}, onError: (e) {
print('errorr : ' + e);
setState(() {
_isListining = false;
});
});
print('streaming');
} catch (e) {
print('not streaming');
print(e);
}
});
}
linke to packages used
https://pub.dev/packages/google_speech
https://pub.dev/packages/mic_stream
so the problem is that microphone streaming is working fine but responseStream from google apis not printing or doing anything
after reading the docs
found this
https://cloud.google.com/speech-to-text/docs/troubleshooting#returns_an_empty_response
and i dont know if it is the problem or not

videoController used after being disposed error in flutter video_player

I am building a videoplayer application in Flutter that plays multiple videos one by one by fetching from the database
After completion of one video we need to transfer videocontroller to another video so first I dispose video controller and initialize with another video
It works fine for 4,5 video sequence and then throw a error like this
throw FlutterError(
'A $runtimeType was used after being disposed.\n'
'Once you have called dispose() on a $runtimeType, it can no longer be used.',
);
Part of my code throwing this error is
void playVideo() async {
if (DateTime.now().isAfter(videoData[index].start_from) &&
DateTime.now().isBefore(videoData[index].end_on)) {
bool played_count = await CountQuery().whenComplete(() {
});
file = File(videoData[index].file_link);
if (file.existsSync() && !played_count) {
isEnd = true;
controller = VideoPlayerController.file(file)
..initialize().then((value) {
setState(() {
controller.play();
});
controller.addListener(() {
// checking the duration and position every time
// Video Completed//
if (controller.value.duration == controller.value.position &&
isEnd) {
setState(() {
isEnd = false;
});
CreateLog("video");
controller.dispose();
PlayNext();
}
});
})
..setLooping(false);
} else {
PlayNext();
}
} else {
PlayNext();
}
}
void PlayNext() {
setState(() {
index++;
if (videoData.length > index) {
// this.asset = videoData[index].file_link;
this.file = File(videoData[index].file_link);
playVideo();
} else {
index = 0;
// this.asset = videoData[index].file_link;
this.file = File(videoData[index].file_link);
playVideo();
}
});
}
Note: I am using video_player: ^2.4.2
I solve this problem by adding controller = null after each dispose

Flutter | audioplayers onDurationChanged Method isn't working on IOS

I'm trying to make some kind of an mp3 player app and i'm using audioplayers package. And it's been working fine on Android, but on IOS the onDurationChanged doesn't seem to be getting called.
And since i'm also showing a slider, it gives an Error on IOS because the max value returns null
Here's my code
class AudioProvider extends ChangeNotifier {
AudioProvider() {
initAudio();
}
AudioPlayer _audioPlayer = AudioPlayer();
Duration totalDuration;
Duration position;
String audioState;
initAudio() {
_audioPlayer.onDurationChanged.listen((updatedDuration) {
totalDuration = updatedDuration; // This doesn't work on IOS, totalDuration == null
notifyListeners();
});
_audioPlayer.onAudioPositionChanged.listen((updatedPosition) {
position = updatedPosition;
notifyListeners();
});
_audioPlayer.onPlayerStateChanged.listen((playerState) {
if (playerState == AudioPlayerState.STOPPED) audioState = "Stopped";
if (playerState == AudioPlayerState.PLAYING) audioState = "Playing";
if (playerState == AudioPlayerState.PAUSED) audioState = "Paused";
notifyListeners();
});
}
playPauseAudio(String url, bool alreadyPlaying) async {
if (!alreadyPlaying) {
position = null;
totalDuration = null;
await _audioPlayer.play(url);
notifyListeners();
}
if (audioState == 'Playing') {
await _audioPlayer.pause();
} else {
await _audioPlayer.resume();
}
notifyListeners();
}
void stop() {
_audioPlayer.stop();
}
void seekToSec(Duration durationToSeek) {
_audioPlayer.seek(durationToSeek);
notifyListeners();
}