vscode-ycy
vscode-ycy copied to clipboard
怎样将嵌入的音频自动播放?
我在你的基础上改了一下加上了audio,但是设置autoplay并不能成功,设置loop是可以循环播放的,但是无法自动播放,代码在浏览器环境下没问题,是vscode有什么限制吗?
const bgmPath = vscode.Uri.file(
path.join(context.extensionPath, "images", "song.ogg")
).with({
scheme: "vscode-resource"
});
this.panel.webview.html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>杨超越</title>
</head>
<body>
<div><h1>cshenger君,代码写久了,休息一下吧~~~</h1></div>
<div><img src="${imagePath}"></div>
<div>
<audio controls="controls" loop="loop" id="audio">
<source src="${bgmPath}" type="audio/ogg" />
Your browser does not support the audio element.
</audio>
</div>
<script>
eval('var audio = document.getElementById("audio");setTimeout(function() {audio.play();}, 2000)');
</script>
</body>
</html>`;
ps: 可以正常显示,就是我得自己手动点击播放
参见 https://github.com/nondanee/vsc-netease-music#known-issue
1.31.0 升级使用 Electron 3.x,受制于 Chrome 66 内核的 Autoplay Policy,用户需先与 Webview 交互才能播放
https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
我回来了,我参考了你的说法,发现确实是这个问题,最终在网上摘了一段AudioContext的代码,自己小改一二实现了自动播放和循环播放的功能。核心代码在下:
const bgmPath = vscode.Uri.file(
path.join(context.extensionPath, "images", "mikuu.mp3")
).with({
scheme: "vscode-resource"
});
this.panel.webview.html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>三玖天下第一(破音)</title>
</head>
<body>
<div><h1>欧尼酱,代码写久了,休息一下吧~~~</h1></div>
<div><img src="${imagePath}" id="img"></div>
<script>
function request (url) {
return new Promise (resolve => {
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
// 这里需要设置xhr response的格式为arraybuffer
// 否则默认是二进制的文本格式
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function () {
// 请求完成,并且成功
if (xhr.readyState === 4 && xhr.status === 200) {
resolve(xhr.response);
}
};
xhr.send();
});
}
function play (context, decodeBuffer) {
let source = context.createBufferSource();
source.buffer = decodeBuffer;
source.connect(context.destination);
source.loop = true;
// 从0s开始播放
source.start(0);
}
async function goPlay() {
// Safari是使用webkit前缀
let context = new (window.AudioContext || window.webkitAudioContext)();
// 请求音频数据
let audioMedia = await request("${bgmPath}");
// 进行decode和play
context.decodeAudioData(audioMedia, decode => play(context, decode));
}
goPlay();
</script>
</body>
</html>`;
@cshenger 赞👍
@cshenger 我尝试了一下,这个应该需要下载插件。我本地没有下载插件,就不行。我调试了几个小时了。
@cshenger 我尝试了一下,这个应该需要下载插件。我本地没有下载插件,就不行。我调试了几个小时了。
@yoloyi 没错啊,插件需要下载下来,在这个基础上改造才可以啊。我这个问题的前提就是下载下来之后咩。 这里贴个最后完成的演示https://www.bilibili.com/video/av49195543
@cshenger 来个PR支持声音播放?