Hello I have a problem with the uploading proccess of audio and video file. In chooseAudio, captureAudio and captureVideo the file that is being uploaded returns empty (video_url for video and audio_url for audio). The chooseVideo returns a valid file if you select one from gallery. but not if you use the camera to make a live video.
This code
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { ActionSheetController, LoadingController, Platform} from '@ionic/angular';
import { Router,ActivatedRoute, NavigationExtras } from "@angular/router";
import { MediaCapture, CaptureVideoOptions, MediaFile, CaptureError, CaptureAudioOptions } from '@awesome-cordova-plugins/media-capture/ngx';
import { File } from '@awesome-cordova-plugins/file/ngx';
//import { Media } from '@capacitor-community/media';
import { Capacitor } from "@capacitor/core";
import { FileTransfer, FileTransferObject, FileUploadOptions } from '@awesome-cordova-plugins/file-transfer/ngx';
import { StreamingMedia, StreamingVideoOptions } from '@awesome-cordova-plugins/streaming-media/ngx';
//import { FileChooser } from '@ionic-native/file-chooser/ngx';
import { Chooser, ChooserResult } from '@awesome-cordova-plugins/chooser/ngx';
import { DomSanitizer,SafeUrl } from '@angular/platform-browser';
import { Camera } from '@awesome-cordova-plugins/camera/ngx';
import { Geolocation } from '@awesome-cordova-plugins/geolocation/ngx';
import { AppData } from '../../services/app-data/app-data';
import { UserData } from '../../services/user-data/user-data';
import { HttpClient } from '@angular/common/http';
import { NativeGeocoder, NativeGeocoderResult, NativeGeocoderOptions } from '@awesome-cordova-plugins/native-geocoder/ngx';
//import { IOSFilePicker } from '@ionic-native/file-picker/ngx';//this one
import { map } from 'rxjs/operators';
import Swal from 'sweetalert2';
import { Events } from '../../services/events/events';
import { TranslateService } from '@ngx-translate/core';
import { Storage } from '@ionic/storage';
import { FileOpener, FileOpenerOptions } from '@capacitor-community/file-opener';
import { Share } from '@capacitor/share';
@Component({
ngOnInit() {
this.audioPlayer = new CapacitorSound();
}
async uploadFile() {
const loading = await this.loadingCtrl.create({
spinner: 'lines', // Change the spinner style (options: 'lines', 'circles', 'dots', 'bubbles', 'crescent')
message: 'Uploading file...',
translucent: true, // Add a translucent overlay
cssClass: 'custom-loading' // Add custom CSS class for further styling
});
await loading.present();
// Simulating file upload process
// Replace this with your actual file upload logic
try {
// Simulating file upload completion after 3 seconds
await new Promise(resolve => setTimeout(resolve, 3000));
// Assuming the file upload is successful
// Dismiss the loading spinner
await loading.dismiss();
// Optionally, show a success message or perform other actions
console.log('File uploaded successfully.');
} catch (error) {
// If an error occurs during file upload
// Dismiss the loading spinner and handle the error
await loading.dismiss();
console.error('File upload failed:', error);
// Optionally, show an error message or perform error handling
}
}
async chooseAudio() {
const actionSheet = await this.actionSheetCtrl.create({
header: this.translation.select_audio_source,
cssClass: 'actionSheetButton',
buttons: [
{
text: this.translation.Load_from_Gallery,
cssClass: 'sendAsMessageButton',
handler: () => {
this.uploadFile();
this.chooser.getFile()
.then((file: any) => {
this.audio_url = file.uri || file.filePath || '';
// Log audio_url to verify it
console.log('audio_url:', this.audio_url);
this.shareAudioFile(this.audio_url);
})
.catch(error => {
console.error(error);
});
}
},
{
text: this.translation.use_mic,
cssClass: 'sendAsMessageButton',
handler: () => {
this.captureAudio();
}
},
{
text: 'Cancel',
role: 'cancel'
}
]
});
await actionSheet.present();
}
async shareAudioFile(audioUrl: string) {
try {
const fileOpenerOptions: FileOpenerOptions = {
filePath: this.audio_url,
contentType: 'audio/mp3', // Adjust content type based on your audio file type
openWithDefault: true,
};
// Log the audio file path to verify it
console.log('File path:', this.audio_url);
await FileOpener.open(fileOpenerOptions);
} catch (error) {
console.error('Error opening file', error);
}
}
async chooseVideo() {
const actionSheet = await this.actionSheetCtrl.create({
header: this.translation.select_video_source,
cssClass: 'actionSheetButton',
buttons: [
{
text: this.translation.Load_from_Gallery,
cssClass: 'uploadVideoButton',
handler: () => {
this.uploadFile();
this.chooser.getFile()
.then((file: any) => {
// Convert video file to a safe URL format
const videoBlob = new Blob([file.data], { type: file.mediaType });
this.video_url = URL.createObjectURL(videoBlob);
this.safeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.video_url);
})
.catch((error) => {
console.error('Error choosing video:', error);
});
}
},
{
text: this.translation.Use_Camera,
cssClass: 'uploadVideoButton',
handler: () => {
this.captureVideo();
}
},
{
text: this.translation.Cancel,
role: 'cancel'
}
]
});
actionSheet.present();
}
captureAudio() {
const options: CaptureAudioOptions = {
limit: 1,
duration: 30
}
this.mediaCapture.captureAudio(options).then((res: MediaFile[]) => {
let capturedFile = res[0];
this.audio_url = capturedFile.fullPath;
}, (err: CaptureError) => console.error(err));
}
captureVideo() {
const options: CaptureVideoOptions = {
limit: 1,
duration: 30
}
this.mediaCapture.captureVideo(options).then((res: MediaFile[]) => {
let capturedFile = res[0];
console.log(res[0]);
this.video_url = capturedFile.fullPath;
this.safeUrl = this.sanitizer.bypassSecurityTrustUrl(
Capacitor.convertFileSrc(capturedFile.fullPath)
);
}, (err: CaptureError) => console.error(err));
}
}
// CapacitorSound class to handle audio playback
class CapacitorSound {
audio: any; // Audio element
isPlayingFlag: boolean = false; // Flag to track if audio is playing
constructor() {
this.audio = new Audio();
this.audio.onended = () => {
this.isPlayingFlag = false;
};
}
play(options: { path: string }) {
this.audio.src = Capacitor.convertFileSrc(options.path); // Convert file path to a format compatible with Capacitor
this.audio.load();
this.audio.play();
this.isPlayingFlag = true;
}
isPlaying(): boolean {
return this.isPlayingFlag;
}
}
works on ios but on android the capture video shows video_url but its empty i doesnt have a file and on capture audio and chooseAudio the audio_url is empty too
<ion-card *ngIf="video_url">
<div class="ion-text-center">
<video webkit-playsinline="true" autoplay playsinline="true" class="cover-video" controls id="video">
<source [src]="safeUrl" type="video/webm">
<source [src]="safeUrl" type="video/mp4">
<source [src]="safeUrl" type="video/ogg">
Your browser does not support the video tag.
</video>
<ion-button fill="clear" (click)="removeVideo()" class="cover-img">
<ion-icon slot="icon-only" name="close"></ion-icon>
</ion-button>
</div>
</ion-card> <ion-card mode="ios" *ngIf="audio_url">
<div class="ion-text-center">
<div class="ion-text-center">
<ion-segment>
<ion-segment-button layout="icon-bottom" *ngIf="!displayPlay" (click)="playAudio()">
<ion-icon name="play"></ion-icon>
<ion-label>Play</ion-label>
</ion-segment-button>
<ion-segment-button layout="icon-bottom" *ngIf="displayPlay" (click)="toggleAudio()">
<ion-icon name="pause"></ion-icon>
<ion-label>Pause</ion-label>
</ion-segment-button>
</ion-segment>
</div>
<ion-button fill="clear" (click)="removeAudio()" class="remove">
<ion-icon slot="icon-only" name="close" ></ion-icon>
</ion-button>
</div>
</ion-card>
i TRYING TO DO THIS BUT I CANT DO YOU SEE ANY PROBLEM ABOUT THE AUDIO_URL AND VIDEO_URL NOT UPLOADED PROPERLY? THANKS