ionic-frameworkcapacitorionic-reactcapacitor-plugin

play audio with url src in ionic / capacitor apps


i'm using react with ionic / capacitor app this code is working fine on android ios and web

   const audioRef = new Audio(
      `data:${audioHex.mimeType};base64,${audioHex.recordDataBase64}`
    );
   audioRef.oncanplaythrough = () => {
      audioRef.play();
    };

but when i try to fetch .mp3 files from url it does not works with android and ios it works fine with web devices.

const audio = new Audio(`https://storage.cloud.google.com/${url}`);
audio.play().catch((error) => console.log("Error playing audio:", JSON.stringify(error)));

i'm unable to find capacitor plugins or any workarounds

i just want to play the mp3 file which are in urls just like its doing in web browsers.


Solution

  • I have never tried this function with web URL (I'm using local sound file). So it may not be the perfect solution for you, but it may direct you in your solution.

        playSound(url: string) {
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
    
        fetch(url)
                .then(response => response.arrayBuffer())
                .then(data => audioContext.decodeAudioData(data))
                .then(buffer => {
                    const launchSource = audioContext.createBufferSource();
                    launchSource.buffer = buffer;
                    launchSource.connect(audioContext.destination);
                    launchSource.start();
                });
    }
    

    Doc :

    declare function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;