hi,
i am fairly new with ionic. I am using ionic 3 with angular 2. My requirement is, i want to download an audio file with .mp3 extention inside my App (only should be inside the app and shouldn’t be accessible outside.)
after downloading the same i wanted to play it using ionic cordova streaming plugin. Can anyone help me with how to achieve this?
since i am able to download file but when trying to access the app crashes. and streaming works fine with a remote URL. but i think i am missing out something for download and so its not able to stream downloaded file.
To do this, I use a combination of the File plugin (for managing files on the device), the File Transfer plugin (for downloading), and the Media plugin (for playing the downloaded files). Here’s a theoretical function that you could put into your provider for downloading and playing an audio file:
import { Injectable } from '@angular/core';
import { File, FileEntry } from '@ionic-native/file';
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer';
import { Media, MediaObject } from '@ionic-native/media';
@Injectable()
export class DownloadAndPlayProvider {
constructor(public file: File, public txfr: FileTransfer, public audio: Media) {}
public download(url: string) {
let ft: FileTransferObject = this.txfr.create();
let fn = this.file.dataDirectory + url.substring(url.lastIndexOf('/') + 1);
ft.download( url, fn ).then(
(fe: FileEntry) => {
let song: MediaObject = this.audio.create(fe.nativeURL);
song.play();
},
err => {
console.log(JSON.stringify(err));
}
);
}
}
@rafibz I haven’t worked with ionic for several years now but what you’re describing is what a cache does. I should also point out (not sure why I didn’t do this in my earlier reply) that generally speaking, streaming and downloading are mutually exclusive options. To play any media file, you either download it and play it locally, or you stream it from a remote location. The code I wrote above represents the “download and play locally” approach.
That said, assuming the code I wrote above still works (I have no clue if it does), there’s a step where you construct a filename to use when storing the file. Since you know what file names your choosing, you should be able to check your local file system to see if a file exists before downloading it again.
@morphatic thank you very much for the fast and detailed response.
I was trying to use the example code above to download external music then play it , but wanted to add the option to check before download if the file already exists on the device.
do you happen to have a snippet for checking if the file exists before downloading?
much appreciated.
Rafi.
Sorry, like I said, it’s been years since I worked on an ionic project and I don’t have any snippets handy other than what you see in this thread. Good luck!