Recorded file neither saving nor playing in cordova-plugin-media (Error code 1) - ionic-framework

I'm using this plugin: cordova-plugin-media with ionic capacitor instead of cordova with command ionic cap sync.
My code:
audioFile: MediaObject;
constructor(private media: Media, private plt: Platform, private file: File) {}
ionViewDidEnter() {
this.plt.ready()
.then(() => {
setTimeout(() => {
this.audioFile = this.media.create(this.file.externalRootDirectory + 'audiofile.mp3');
this.audioFile.onStatusUpdate.subscribe(status => console.log('status: ', status));
this.audioFile.onSuccess.subscribe(() => console.log('Action is successful'));
this.audioFile.onError.subscribe(error => console.log('Error: ', error));
}, 1000);
})
.catch(err => console.log('ready error: ', err));
}
record() {
// When record button clicked
this.audioFile.startRecord();
}
stop() {
// When stop button clicked
this.audioFile.stopRecord();
this.audioFile.play();
}
When I clicked Record btn, record() was executed and output was: Error: 1 and when I stopped recording than the output was status: 4 and Action is successful
I expected to either play the recording or get audiofile.mp3 in the file manager of my android device but I didn't observed any of it. Can someone help me with this issue?
What I tried:
I thought that its extension issue so I tried replacing mp3 with 3gp and m4a
I tried removing file:// from file.externalRootDirectory with slice method - file.externalRootDirectory.slice(7)
Instead of externalRootDirectory I also tried applicationDirectory and externalDataDirectory
I also submitted my issue on their github repository but I didn't got any response yet
I tried finding solutions on other communities and stackoverflow itself but problem still exists

Android 10 uses a new file system therefore plugins that have not updated themselves might not read/create files on Android 10.
You need to manually add this line in your manifest file : android:requestLegacyExternalStorage="true"
Open your project in Android Studio and open the AndroidManifest file.
In tag inside your manifest file, add android:requestLegacyExternalStorage="true"
Rebuild your project

Related

Ionic v5 web media capture with capacitor - cordova_not_available

I am building an app with Ionic 5, Capacitor 2 and Angular 11.
I need to capture video and audio using the media capture cordova plugin.
I installed the following modules:
npm install cordova-plugin-media-capture
npm install #ionic-native/media-capture
And added MediaCapture to the providers of my app module.
Then I call mediaCapture.captureVideo() to retrieve a video ; unfortunately an exception is thrown when testing on a browser: cordova_not_available
The github repo states this plugin is web-compatible, and its sources have a browser implementation. However the window.navigator.device.capture is missing to make this plugin work.
Is it a bad configuration from my side? Or this cordova plugin wouldn't be compatible with capacitor?
I made a repro : https://stackblitz.com/edit/ionic-v5-media-capture-capacitor?file=src/app/app.component.ts
Thank you for your help
I wrote a regular Angular version for the web, if anyone need it:
async browserCapture() {
const stream: MediaStream = await navigator.mediaDevices.getUserMedia(this.constraints);
const recorder = new MediaRecorder(stream, {mimeType: 'ogg'});
const chunks: Blob[] = [];
recorder.ondataavailable = (event: BlobEvent) => {
if (event.data && event.data.size > 0) {
chunks.push(event.data);
this.zone.run(() => {
this.recordChunks = [...chunks];
this.cd.markForCheck();
});
}
};
this.recorder.onstop = () => {
this.zone.run(() => {
stream.getTracks().forEach(t => t.stop());
if (chunks?.length) {
this.upload(new Blob(chunks, {type: 'ogg'})); // use the blob result
}
});
};
recorder.start(500);
}

Download pdf file from firebase storage ioinc 5

I am trying to download pdf file in ionic 5 application, which is stored in firebase storage i tried using filetransfer but file not downloading in my device it gives entry url this
file:///data/user/0/io.ionic.starter/files/test.pdf
Here the Download function
download(downloadUrl: string) {
console.log(downloadUrl);
this.fileTransfer.download(downloadUrl,this.file.dataDirectory +'test.pdf').then((entry) => {
console.log('download complete: ' + entry.toURL());
}, (error) => {
});
}
You need to add
android:requestLegacyExternalStorage="true"
inside AndroidMenifest.xml > application tag like below screenshot. It's required to add in the android 11 version.

How can i check if file exist with ionic

i am building a mobile app for both android and iOS i want to check if a directory exist in the users sd card or in-built memory, if the directory doesn't exist, then i will create the directory.
I checked the docs on ionic file transfer docs but i can't find anything useful, i searched online but found some code but its not working, the name of the directory that I want to create is softik, Here is the code
public storageDirectory:any;
download() {
this.chkmkDir().then(async ()=>{
const fileTransfer: FileTransferObject = this.fileTransfer.create();
this.storageDirectory = `${this.file.externalRootDirectory}test.mp4`;
fileTransfer.onProgress((progressEvent)=>this.progress=Math.round((progressEvent.loaded / progressEvent.total) * 100))
fileTransfer.download(this.url,this.storageDirectory + 'test.mp4', true).then((entry) =>
console.log('Berhasil download dan tersimpan di : ' + this.storageDirectory + "test.jpeg"),
error => console.log('gagal : ' + JSON.stringify(error)),
);
}).catch(err=>console.log())
}
chkmkDir(){
return new Promise((resolve, reject)=>{
this.file.checkDir(this.file.externalRootDirectory, 'softik').then(res=>resolve()
).catch(err => {
this.file.createDir(this.file.externalRootDirectory, 'softik',false).then(res =>resolve())
.catch(err=>reject(JSON.stringify(err)));
});
})
}
Pls what am i going wrong
first you should use File plugin
then you can search for file or Directory
see this docs https://ionicframework.com/docs/v3/native/file/#checkFile

Unable to register the service worker

My app is under ionic 4 angular.
I've installed the pwa part with :
ng add #angular/pwa --project app
Then I build with : ionic build --prod
and deployed to firebase with : firebase deploy
But I have 2 problems :
1) the banner "add to screen" is not shown when I browse the app from my android phone.
Even with this code on the root url :
showBtn: boolean = false;
deferredPrompt;
constructor(private modalController: ModalController, public authUser: AuthUserService, private router: Router){}
ionViewWillEnter(){
window.addEventListener('beforeinstallprompt', (e) => {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later on the button event.
this.deferredPrompt = e;
// Update UI by showing a button to notify the user they can add to home screen
this.showBtn = true;
});
//button click event to show the promt
window.addEventListener('appinstalled', (event) => {
alert('installed');
});
if (window.matchMedia('(display-mode: standalone)').matches) {
alert('display-mode is standalone');
}
}
2) When I launch lighthouse audit I get this warning :
Does not register a service worker that controls page and start_url
I've tried to uninstall, reinstall, rebuild everything but nothing works.
On ionic docs I can't find any clue to fix this problem.
After many days I was able to make it works.
First I add this following snippet to the firebase.json file to the hosting property:
{
"source": "ngsw-worker.js",
"headers": [
{
"key": "Cache-Control",
"value": "no-cache"
}
]
}
Then I add this script in my index.html :
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('ngsw-worker.js')
.then(() => console.log('service worker installed'))
.catch(err => console.error('Error', err));
}
</script>
Now it works !

Ionic native Transfer plugin's `file.dataDirectory` shows error

I'm going to use the Ionic native Transfer plugin as shown below.
Problem is here this.file.dataDirectory.It shows error like [ts] Property 'dataDirectory' does not exist on type 'File'..Can you tell me what is the solution for this?
download() {
const fileTransfer: TransferObject = this.transfer.create();
const url = 'http://www.example.com/file.pdf';
fileTransfer.download(url, this.file.dataDirectory + 'file.pdf').then((entry) => {
console.log('download complete: ' + entry.toURL());
}, (error) => {
// handle error
});
}
Oh.. My bad :(
I have to install File plugin too :D
$ ionic cordova plugin add cordova-plugin-file --save
$ npm install --save #ionic-native/file