native-audio icon indicating copy to clipboard operation
native-audio copied to clipboard

How download audio file and play with native-audio plugin?

Open lsantaniello opened this issue 2 years ago • 3 comments

I’d like to play mp3 audio in my ionic capacitor app. I download file from server and then I want play it.

I used:

@capacitor/filesystem in order to download file @capacitor-community/native-audio in order to play audio Download file:

    let option = {
      path: "sample.mp3",
      url: "https://file-examples.com/storage/fe9f92926365baacd9d565f/2017/11/file_example_MP3_700KB.mp3",
      directory: Directory.Data,
      recursive: true
    } as DownloadFileOptions;
    
    try {
      const result = await Filesystem.downloadFile(option);
      console.log('Wrote file', result);
      this.downloadUri = result.path!; //save path into global var
      alert("OK " + this.downloadUri);
    } catch(e) {
      console.error('Unable to write file', e);
      alert("ERROR");
    }

Play audio

    await NativeAudio.preload({
      assetId: "sample",
      assetPath: this.downloadUri, //use saved path
      audioChannelNum: 1,
      isUrl: true
    });

    await NativeAudio.play({
      assetId: 'sample'
    });

Download is OK but when I play I receve error:

Wrote file {path: '/DATA/ciao.mp3', blob: Blob}
Not allowed to load local resource: file:///DATA/ciao.mp3

I’m testing on web browser (ionic serve mode). If I use local audio file (stored into assets/sound folder), it works

could you lease help me?

lsantaniello avatar Feb 02 '24 21:02 lsantaniello

can you resolve this?

GBurgardt avatar Mar 03 '24 23:03 GBurgardt

can you resolve this?

not solved.

lsantaniello avatar Mar 22 '24 14:03 lsantaniello

You can resolve this using my plugin: https://github.com/BarnabasSzabolcs/capacitor-play-audio-from-url npm install capacitor-play-audio-from-url then PlayAudioFromUrl.play({url}) (It does not download the file, it only plays it (on iphone and on android). On the web, it caches the downloaded audio, so that the browser is less likely to deny playing the audio, if you want to play many audios one after another. ref. https://developer.chrome.com/blog/autoplay )

BarnabasSzabolcs avatar Apr 28 '24 16:04 BarnabasSzabolcs