When I write a blog, I want to add my favorite music to the blog webpage so that I can have a more pleasant mood while writing and reading. At this time, we need to use the audio
tag.
<audio src=""></audio>
The audio tag also has many useful attributes, the commonly used ones are as follows:
- src - This one is self-explanatory
- autoplay - If this attribute is present, the audio will start playing as soon as it is ready
- controls - Display audio controls in the webpage
- loop - Loop the audio playback
- muted - Mute by default
However, when I tried to set autoplay, I found that Chrome strongly dislikes autoplay and directly restricts the enabling of this attribute from the root. This means that this attribute is disabled and automatic playback is not allowed when opening the webpage without any interaction.
But thinking about it carefully, this approach is actually more beneficial to the users. Assuming the user is using mobile data, directly autoplaying videos or audios would cause them losses. Even some ads autoplay, which directly affects the user experience. So, I actually agree with Chrome's approach.
But wait, that's not right. My goal is to solve this problem, not praise Google. I want to add my favorite music to my personal blog, so I found a workaround. I directly simulate an event, and when the mouse clicks anywhere on the webpage, it automatically triggers the autoplay effect. Let's see the code.
<script>
function toggleSound() {
var music = document.getElementById("vd");
// Get the ID
console.log(music);
console.log(music.paused);
if (music.paused) {
// Check if it is paused
music.paused=false;
music.play();
// If it is paused, play it
}
}
setInterval("toggleSound()",1);
</script>
After handling it this way, when inserting audio and clicking anywhere on the webpage, the play effect will be triggered. However, there are pros and cons to everything. By doing this, once the playback is started, the pause function cannot be enabled, which means it will keep playing.
If it is for a personal blog like mine, this drawback doesn't have a big impact. I'll record this method here.