Search code examples
javascriptgoogle-chromegoogle-chrome-extensionmp3audio-capture

Chrome extension that can play sounds through the microphone


I'm trying to create an extension that can launch sounds through the microphone, mp3 sounds.

For example I want that a user enters a google meet call or any other service and that by pressing a button in the** popup.html** a sound is triggered that all the people in the conversation can hear.


Solution

  • Use software to redirect sound from speakers to microphone on your sound card (there are many apps) or you can create your own with c#

    to play sound from the chrome extension use offscreen

    manifest.json

    "permissions": ["offscreen"]
    

    background.js

    /**
     * Plays audio files from extension service workers
     * @param {string} source - path of the audio file
     * @param {number} volume - volume of the playback
     */
    async function playSound(source = 'default.wav', volume = 1) {
        await createOffscreen();
        await chrome.runtime.sendMessage({ play: { source, volume } });
    }
    
    // Create the offscreen document if it doesn't already exist
    async function createOffscreen() {
        if (await chrome.offscreen.hasDocument()) return;
        await chrome.offscreen.createDocument({
            url: 'offscreen.html',
            reasons: ['AUDIO_PLAYBACK'],
            justification: 'testing' // details for using the API
        });
    }
    

    offscreen.html

    <script src="offscreen.js"></script>
    offscreen.js
    
    // Listen for messages from the extension
    chrome.runtime.onMessage.addListener(msg => {
        if ('play' in msg) playAudio(msg.play);
    });
    
    // Play sound with access to DOM APIs
    function playAudio({ source, volume }) {
        const audio = new Audio(source);
        audio.volume = volume;
        audio.play();
    }