javascript playsound chrome extension Manifest V3

如何在 chrome extension 裡播放音樂:

程式碼:

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();
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *