I need to record voice and send it with Firebase. I am using flutter_sound but the plugin doesn't generate a recorded file and I don't know why.
Future<String> result =flutterSound.startRecorder(null,androidEncoder: AndroidEncoder.AMR_WB);
result.then((value){
print('startRecorder: $value');
_recorderSubscription = flutterSound.onRecorderStateChanged.listen((e) {
DateTime date = new DateTime.fromMillisecondsSinceEpoch(e.currentPosition.toInt());
String txt = DateFormat('mm:ss:SS', 'en_US').format(date);
print(txt);
});
});
Related
How can I get the sound I recorded in a file in flutter as a string(text) every word of it?
as an example, he will say hello world in the audio file.How can I get this as a string
String getText = "hello world";
i know about google's speech-to-text product, but it seems too expensive, isn't there another way for me to do it?
Try this package
google_speech: ^2.0.1
To convert audio to text use the code below
Future<List<int>> _getAudioContent(String name) async {
final directory = await getApplicationDocumentsDirectory();
final path = directory.path + '/$name';
return File(path).readAsBytesSync().toList();
}
final audio = await _getAudioContent('test.wav');
final response = await speechToText.recognize(config, audio);
print(response);
Recently I am using a package named flutter_sound v9.1.7. Here are some of the codes.
String _mPath = 'tau_file.mp4';
Codec _codec = Codec.aacMP4;
File? file;
FlutterSoundPlayer? _mPlayer = FlutterSoundPlayer();
FlutterSoundRecorder? _mRecorder = FlutterSoundRecorder();
void record() async {
_mRecorder!
.startRecorder(
toFile: _mPath,
codec: _codec,
audioSource: AudioSource.microphone,
)
.then((value) {});
setState(() {
recording = true;
});
}
I have succeeded in recording and playing audio, but when I finish recording and try to analyze the seeming audio file tau_file.mp4, such like get the length of the file, an error occurred:
Cannot retrieve length of file, path = 'tau_file.mp4' (OS Error: No such file or directory, errno = 2).
The analysis code is here:
file = File(_mPath);
print(file?.path);
print(file?.absolute);
print(file?.length.toString());
I tried to seek answer in source codes, but only found an interface... So is the audio really be written to the file tau_file.mp4? Or maybe the process of analysis is wrong?
This is the first time that I use flutter_sound. Thanks for your help.
void stopRecorder() async {
await _mRecorder!.stopRecorder().then((value) {
setState(() {
//var url = value;
recordedUrl = value;
debugPrint('path : -------- $recordedUrl');
_mplaybackReady = true;
});
});
}
This is your recorded files url, when you stop the record you can get it.
The document includes this code. It gives you //var url = value;. Then you can handle it. like var recordedFile = File(url);. it's not a temporary one. You can upload it somewhere or whatever you like.
I have this page where the camera is initialized and ready with a button that will record and stop the video, so I tried this :
FlatButton(
onPressed: () => {
!isRecording
? {
setState(() {
isRecording = true;
}),
cameraController.prepareForVideoRecording(),
cameraController.startVideoRecording('assets/Videos/test.mp4')
}
: cameraController.stopVideoRecording(),
},
............
but throws this error : nhandled Exception: CameraException(videoRecordingFailed, assets/Videos/test.mp4: open failed: ENOENT (No such file or directory)).
I don't understand, I don't want to open this file I want to save it there, Is there sth wrong with my code ?
In the new version, static method startRecordingVideo doesn't take any string parameter.
When you want to start the recording just see whether a video is already getting recorded, if not start
if (!_controller.value.isRecordingVideo) {
_controller.startVideoRecording();
}
and when you want to finish the recording you can call the static method stopVideoRecording() and it will give you a object of the class XFile, it will have the path to your video.
if (_controller.value.isRecordingVideo) {
XFile videoFile = await _controller.stopVideoRecording();
print(videoFile.path);//and there is more in this XFile object
}
This thing has worked for me. I am new to flutter please improve my answer if you know more.
You are trying to save a video in your assets folder which is not possible ,
What you need to do is to save to device locally either common folders like downloads or app directory.
Here is an example of how to go about it
dependencies:
path_provider:
Flutter plugin for getting commonly used locations on host platform
file systems, such as the temp and app data directories.
We will be saving the video to app directory.
We need to get the path to the directory where the file is or will be. Usually a file is put in the application's document directory, in the application's cache directory, or in the external storage directory. To get the path easily and reduce the chance of type, we can use PathProvider
Future<String> _startVideoRecording() async {
if (!controller.value.isInitialized) {
return null;
}
// Do nothing if a recording is on progress
if (controller.value.isRecordingVideo) {
return null;
}
//get storage path
final Directory appDirectory = await getApplicationDocumentsDirectory();
final String videoDirectory = '${appDirectory.path}/Videos';
await Directory(videoDirectory).create(recursive: true);
final String currentTime = DateTime.now().millisecondsSinceEpoch.toString();
final String filePath = '$videoDirectory/${currentTime}.mp4';
try {
await controller.startVideoRecording(filePath);
videoPath = filePath;
} on CameraException catch (e) {
_showCameraException(e);
return null;
}
//gives you path of where the video was stored
return filePath;
}
I am developing an app that fetches a custom object from my REST API. The object's class is called MyItem and it looks like this:
class MyItem {
String title;
String profilePicURL;
String videoURL;
}
As you can see, the class contains two URLs, that points to a png and mp4 files.
I would like to implement a feature, which allows the user to download the object, in order to access its content offline. I have no problem saving the title property, but how can I save the two URLs (because I don't want the URL itself to be saved, I would like to save the file it points to).
Any idea what is the best way doing that in Flutter and Dart?
Thank you!
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
var directory = await getApplicationDocumentsDirectory();
Dio dio = Dio();
//Below function will download the file you want from url and save it locally
void Download(String title, String downloadurl) async{
try{
await dio.download(downloadurl,"${directory.path}/$title.extensionoffile",
onReceiveProgress: (rec,total){
print("Rec: $rec, Total:$total");
setState(() {
//just to save completion in percentage
String progressString = ((rec/total)*100).toStringAsFixed(0)+"%";
}
);
});
}
catch(e){
//Catch your error here
}
}
Now again wherever you want just use
var directory = await getApplicationDocumentsDirectory();
String filepath = "{directory.path}/filename.fileextension";
Now you can use this Image.file('filepath'); //to display those image
also you can use
video player plugin
where again VideoPlayerController.file('filepath') //to show video but read documention properly
These are just a whole steps or a broader view, you need to use them as a map and build your code.That is have a proper file name and extension saved or correctly fetched or mapped
Actually I need to send a voice message to my contacts using flutter.I have searched a lot.But I didn't get any idea on this.Is there any way to do this.?
if you want to share a voice message in a chat(e.g firebase chat) you can use flutter_sound, send a voice file to your cloud, and you can play it again with flutter_sound too.
You can use the audio_recorder package:
https://pub.dev/packages/audio_recorder
// Import package
import 'package:audio_recorder/audio_recorder.dart';
// Check permissions before starting
bool hasPermissions = await AudioRecorder.hasPermissions;
// Get the state of the recorder
bool isRecording = await AudioRecorder.isRecording;
// Start recording
await AudioRecorder.start(path: _controller.text, audioOutputFormat: AudioOutputFormat.AAC);
// Stop recording
Recording recording = await AudioRecorder.stop();
print("Path : ${recording.path}, Format : ${recording.audioOutputFormat}, Duration : ${recording.duration}, Extension : ${recording.extension},");