Flutter App for encryption an audio for secure - flutter

I have a project with encrypt an audio for secure my data audio and when the user purchase they can play the audio, but until now didn't find how to do that. I found another way by converting the audio data into a string and then encrypting it, I found a code but it's incomplete so I'm still confused about using it.
import 'dart:io';
import 'dart:typed_data';
import 'package:file_picker/file_picker.dart';
import 'package:path_provider/path_provider.dart';
class MediaFile {
Future<String> get docPath async {
Directory appDocDir = await getApplicationDocumentsDirectory();
return appDocDir.path;
}
Future<Uint8List> get audioFileData async {
final String path = await docPath;
final String theFilePath = '$path/test.mp3';
final File theFile = new File(theFilePath);
if (await theFile.exists()) {
return await theFile.readAsBytes();
} else {
File file = await FilePicker.getFile();
return await file.readAsBytes();
}
}
Future<String> dataToString() async {
Uint8List data = await audioFileData;
return new String.fromCharCodes(data);
}
Future<File> saveMediaAsString(String fileName, String fileContent) async {
String path = await docPath;
Directory dataDir = new Directory('$path/data');
if (await dataDir.exists()) {
File file = new File('$path/data/$fileName');
return file.writeAsString(fileContent);
}
await dataDir.create();
File file = new File('$path/data/$fileName');
return file.writeAsString(fileContent);
}
Future<String> readFromStringMediaFile(String fileName) async {
String path = await docPath;
File file = new File('$path/data/$fileName');
return file.readAsString();
}
Uint8List stringToData(dataStr) {
List<int> list = dataStr.codeUnits;
return new Uint8List.fromList(list);
}
Future<File> createAudioFile(String fileName, Uint8List bytes) async {
String path = await docPath;
File file = new File('$path/$fileName');
return await file.writeAsBytes(bytes);
}
//here you can see how to use them
Future<File> testFile() async {
String dataStr = await dataToString();
File savedFile = await saveMediaAsString('codedFile', dataStr);
String contentSavedFile = await readFromStringMediaFile('codedFile');
Uint8List bytes = stringToData(contentSavedFile);
return await createAudioFile('test.mp3', bytes);
}
}

Related

Cannot get the download link after uploading files to firebase storage Flutter

so this is the my file picking and file upload code
class Storage with ChangeNotifier {
PlatformFile? pickedFile;
UploadTask? uploadTask;
Future uploadFile() async {
final path = 'files/${pickedFile!.name}.png';
final file = File(pickedFile!.path!);
final ref = FirebaseStorage.instance.ref().child(path);
ref.putFile(file);
try {
final snapshot = await uploadTask!.whenComplete(() {});
final urlDownload = await snapshot.ref.getDownloadURL();
print(urlDownload);
} catch (e) {
print("this is the error $e " );
}
}
void pickFile() async {
FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null) {
File file = File(result.files.single.path!);
pickedFile = result.files.first;
} else {
print("no image picked");
}}}
the code works for upload the image but after that i didnt get any download link, the error is "Null check operator used on a null value" i dont know how to fix it, im still new in this topic, help please
i got the answer, need to change the uploadFile method to this
Future uploadFile() async {
final path = 'files/${pickedFile!.name}.png';
final file = File(pickedFile!.path!);
FirebaseStorage storage = FirebaseStorage.instance;
Reference ref = storage.ref().child(path);
UploadTask uploadTask = ref.putFile(file);
uploadTask.then((res) {
res.ref.getDownloadURL();
});
try {
final snapshot = await uploadTask.whenComplete(() {});
final urlDownload = await snapshot.ref.getDownloadURL();
print(urlDownload);
} catch (e) {
print("this is the error $e " );
}
}

Flutter 'File' can't be assigned to 'XFile'

I have a function to save network image to local cache files, but I have a trouble when store the list file that I downloaded to List<XFile>. Here is my download function:
List<XFile>? imageFileList = [];
Future<File> downloadImage(url, filename) async {
var httpClient = HttpClient();
try {
var request = await httpClient.getUrl(Uri.parse(url));
var response = await request.close();
var bytes = await consolidateHttpClientResponseBytes(response);
final dir = await getTemporaryDirectory();
File file = File('${dir.path}/$filename');
await file.writeAsBytes(bytes);
print('downloaded file path = ${file.path}');
return file;
} catch (error) {
print('download error');
return File('');
}
}
is there any way so I can save the file to imageFileList as :
imageFileList!.add(file);
Convert the file to XFile:
XFile file = new XFile(file.path);
Change your list type:
from this:
List<XFile>? imageFileList = [];
to this:
List<File>? imageFileList = [];
final ImagePicker _picker = ImagePicker();
getImage() async {
var images = await _picker.pickMultiImage();
images!.forEach((image) {
setState(() {
_imageFileList!.add(File(image.path));
});
});
}

Flutter - How to save and play a recorded audio file?

I, for the life of me, can't figure this out. All I am trying to do is record an audio (as in a sound/voice recorder) and later be able to play it.
Recorder class:
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
//String _pathToAudio = '/sdcard/myAudio.aac';
String _fileName = 'myAudio.aac';
String _path = "/storage/emulated/0";
class Recorder {
FlutterSoundRecorder? _recorder;
bool _isRecorderInitialized = false;
bool get isRecording => _recorder!.isRecording;
Future init() async {
_recorder = FlutterSoundRecorder();
//final directory = "/sdcard/downloads/";
//Directory? extStorageDir = await getExternalStorageDirectory();
//String _path = directory.path;
final status = await Permission.microphone.request();
if (status != PermissionStatus.granted) {
throw RecordingPermissionException('Recording permission required.');
}
await _recorder!.openAudioSession();
_isRecorderInitialized = true;
}
void _writeFileToStorage() async {
File audiofile = File('$_path/$_fileName');
Uint8List bytes = await audiofile.readAsBytes();
audiofile.writeAsBytes(bytes);
}
void dispose() {
_recorder!.closeAudioSession();
_recorder = null;
_isRecorderInitialized = false;
}
Future record() async {
if (!_isRecorderInitialized) {
return;
}
print('recording....');
await _recorder!.startRecorder(
toFile: '$_fileName',
//codec: Codec.aacMP4,
);
}
Future stop() async {
if (!_isRecorderInitialized) {
return;
}
await _recorder!.stopRecorder();
_writeFileToStorage();
print('stopped....');
}
Future toggleRecording() async {
if (_recorder!.isStopped) {
await record();
} else {
await stop();
}
}
}
Currently the error I am getting is "Cannot open file, path = '/storage/emulated/0/myAudio.aac' (OS Error: No such file or directory, errno = 2)".
I am using flutter_sound
Try initializing your file path by using path_provider.
Add these 2 lines to the beginning of your init function.
final directory = await getApplicationDocumentsDirectory();
_path = directory.path; // instead of "/storage/emulated/0"
Not sure how you're trying to access and play that file but on my end it at least cleared the error.
String _fileName = 'Recording_';
String _fileExtension = '.aac';
String _directoryPath = '/storage/emulated/0/SoundRecorder';
This is what I have currently and it's working.
void _createFile() async {
var _completeFileName = await generateFileName();
File(_directoryPath + '/' + _completeFileName)
.create(recursive: true)
.then((File file) async {
//write to file
Uint8List bytes = await file.readAsBytes();
file.writeAsBytes(bytes);
print(file.path);
});
}
void _createDirectory() async {
bool isDirectoryCreated = await Directory(_directoryPath).exists();
if (!isDirectoryCreated) {
Directory(_directoryPath).create()
// The created directory is returned as a Future.
.then((Directory directory) {
print(directory.path);
});
}
}
void _writeFileToStorage() async {
_createDirectory();
_createFile();
}

How to print a PDF file in Flutter

Here is my code
Future<File> _downloadFile(String url, String filename) async {
http.Client _client = new http.Client();
var req = await _client.get(Uri.parse(url));
var bytes = req.bodyBytes;
// String dir = (await getApplicationDocumentsDirectory()).path;
String dir = await ExtStorage.getExternalStoragePublicDirectory(
ExtStorage.DIRECTORY_DOWNLOADS);
File file = new File('$dir/$filename');
await file.writeAsBytes(bytes);
return file;
}
/// Prints a sample pdf printer
void printPdfFile() async {
var file = await _downloadFile(
"http://www.africau.edu/images/default/sample.pdf", "test.pdf");
await FlutterPdfPrinter.printFile(file.path);
}
I am implementing print PDF files which is saved in my device. When trying to print the document I am getting error like "A problem occurred configuring project ':flutter_pdf_printer'."
I am using flutter_pdf_printer dependency to print PDF files.
Convert your string url to URI, please make sure you are adding http
http: ^0.13.4
import 'package:http/http.dart' as http;
Uri uri = Uri.parse('Your link here');
http.Response response = await http.get(uri);
var pdfData = response.bodyBytes;
await Printing.layoutPdf(onLayout: (PdfPageFormat
format) async => pdfData);

A way to serve a file through http without loading it into ram? Help. Flutter / Dart

So I've created an app that creates a static file server using the httpserver API and I used VirtualDirectory to generate a list of items in a specified directory on Android. The app is working but whenever there is a large file it crashes and from what I understand it is because it loads way too much data into the memory.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'dart:io';
import 'package:http_server/http_server.dart';
import 'package:path_provider/path_provider.dart';
void main(){
runApp(MaterialApp(
home:HomePage(),
));
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
static Future<String> get getFilePath async{
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
static Future<File> getFile(String fileName) async{
final path = await getFilePath;
return File('$path/$fileName');
}
static Future<File> saveToFile(var data, String filePath, String fileName) async{
print("filePath+fileName: " + filePath+fileName);
final file = await getFile(filePath+fileName);
return file.writeAsString(data);
}
static Future<void> createDir(String filePath) async{
final path = await getFilePath;
Directory('$path/$filePath').create(recursive: true);
}
static Future<String> readFromFile(String filePath, String fileName) async{
try{
final file = await getFile('$filePath$fileName');
String fileContents = await file.readAsString();
return fileContents;
}catch(e){
final assetFile = await rootBundle.loadString('assets/$filePath$fileName');
if(filePath == ''){
await saveToFile(assetFile, '$filePath', '$fileName');
}else{
await createDir(filePath);
await saveToFile(assetFile, '$filePath', '$fileName');
}
print('copying the file from assets');
return '';
}
}
String data = '';
String rootDirPathStr;
assetFolder() async{
final v = await getFilePath;
Directory('$v').create(recursive: true);
await createDir('dist/css');
await createDir('dist/js');
await readFromFile('','index.html');
await readFromFile('dist/css','/style.min.css');
await readFromFile('dist/js','/serverCom.js');
await readFromFile('dist/js','/main.js');
await readFromFile('dist/js','/files.js');
await readFromFile('dist/js','/index.json');
}
serverInit() async{
// setState(() {
// data = "Server running on IP : "+server.address.toString()+" On Port : "+server.port.toString();
// });
//getting the dir
final rootDir = await getApplicationDocumentsDirectory();
rootDirPathStr = rootDir.path;
print("rootDirPathStr: " + rootDirPathStr);
//getting the dir
HttpServer server = await HttpServer.bind(InternetAddress.anyIPv4, 8080);
print("Server running on IP : "+InternetAddress.anyIPv4.toString()+" On Port : "+server.port.toString());
VirtualDirectory rootVirDir = VirtualDirectory(rootDirPathStr)
..allowDirectoryListing = true;
VirtualDirectory userFilesVirDir = VirtualDirectory('/storage/emulated/0/IDM/')
..allowDirectoryListing = true;
// await userFilesVirDir.serve(server);
await for (HttpRequest request in server) {
String requestUriPath = request.uri.path;
String requestUriQuery = request.uri.query;
print('requestUriPath: $requestUriPath and requestUriQuery: $requestUriQuery');
if(requestUriPath == '/' && requestUriQuery == '') {
final path = await getFilePath;
await rootVirDir.serveFile(File('$path/index.html'), request);
}else if(requestUriQuery == 'file'){
print('file requested');
try{
await userFilesVirDir.serveRequest(request);
}catch(e){
print("error On file requested: $e");
}
}
else{
await rootVirDir.serveRequest(request);
}
}
}
#override
void initState() {
assetFolder();
serverInit();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child:Text('data'),
),
);
}
}
https://pub.dev/packages/shelf can return a ByteStream as the response... allowing virtually unlimited results. As reported in https://pub.dev/documentation/shelf/latest/shelf/Response/Response.ok.html:
body is the response body. It may be either a String, a List<int>, a Stream<List<int>>, or null to indicate no body.
So you can just open a stream on a large file, and hand it (perhaps through a StreamTransformer) directly in the response. I don't think http_server can do that.