如何在hugo生成的网页中插入嵌入式音乐
Table of Contents
缘起
在我发布了在网页中嵌入视频的视频后,有网友问如何插入音乐文件并自动播放。就有了这个视频。
定义Shortcode
以 https://music.163.com/#/song?id=1304708603 为例:
先分析一下嵌入代码的格式
<iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=1304708603&auto=1&height=66"></iframe>
定义 shortcode 代码
<iframe frameborder="0" border="1" marginwidth="0" marginheight="0" width=333 height=77 src="//music.163.com/outchain/player?type=2&id={{.Get 0 }}&auto=1&height=66" >
到这一步,实现和插入视频的方式是一致的。但是尽管有 auto=1 这个参数,但由于目前浏览器的各类限制,自动播放这个功能是不能实现的。
实现自动播放
使用javascript方式实现自动播放,这个方便也是参考了:
html背景音乐自动播放怎么实现? - 墨语的回答 - 知乎 https://www.zhihu.com/question/472325267/answer/1999266585
进行相应的修改后的shortcode代码
<audio id="music1" controls autoplay="autoplay" loop="loop" preload="auto"> <source src="http://music.163.com/song/media/outer/url?id={{.Get 0 }}.mp3" type="audio/mpeg" /> </audio> <script> var audio = document.getElementById('music1'); $("#btn").bind( "touchstart", function bf() { if(audio !== null) { //检测播放是否已暂停.audio.paused 在播放器播放时返回false. //alert(audio.paused); if(audio.paused) { audio.play(); //audio.play();// 这个就是播放 $("#btn").addClass("active") } else { audio.pause(); // 这个就是暂停 $("#btn").removeClass("active") } } }) </script>
使用
下面的2个音乐第一个是直接使用了网易云音乐的分享代码,第二个是会自动播放的代码。