1

How to play sound/audio from phone storage on ionic 7?

I tried using cordova-plugin-nativeaudio like below

const url = await Filesystem.getUri({
    directory: Directory.Documents,
    path: 'test.ogg',
})

window.plugins.NativeAudio.preloadSimple('test', url.uri, function (msg) {
}, function (msg) {
    console.log('error: ' + msg);
});

window.plugins.NativeAudio.play('test');

and it's returns:

Msg: error: java.io.FileNotFoundException: file:///storage/emulated/0/Documents/test.ogg

If the path is from my app public path it works. But if it from phone storage it doesn't work.

On the documentation says:

assetPath - the relative path or absolute URL (inluding http://) to the audio asset.

But why I tried absolute URL of phone storage still fail? I already give storage permission to my app.

Muhammad Dyas Yaskur
  • 6,914
  • 10
  • 48
  • 73

1 Answers1

1

I found this answer that seems cordova-plugin-nativeaudio is not work with phone storage. But I know the work around just using HTML5 audio:

import {Filesystem, Directory} from '@capacitor/filesystem';
import {Capacitor} from '@capacitor/core';

const url = await Filesystem.getUri({
    directory: Directory.Documents,
    path: 'secrets/test.ogg',
})

const fileSrc = Capacitor.convertFileSrc(url.uri);
const audio = new Audio(fileSrc);
audio.play();

Actually I tried new Audio(url.uri) but doesn't work(file permission issue), after I convert that path using convertFileSrc() method first, it works.

Muhammad Dyas Yaskur
  • 6,914
  • 10
  • 48
  • 73