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, commonly used ones include:
- src - I don't need to explain this, those who understand will understand
- autoplay - If this attribute appears, the audio will play immediately after it is ready
- controls - Display audio controls in the webpage
- loop - Loop playback
- muted - Muted by default
But when I tried to set autoplay, I found that Chrome strongly dislikes autoplay and directly restricts the use of this attribute from the root. This means that the attribute is disabled and autoplay is not allowed when opening the webpage without interaction.
But thinking about it carefully, this approach is actually more beneficial for users. Suppose the user is using mobile data, if videos or audios autoplay directly, it will cause loss to the user. Even some ads will 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 to praise Google. I want to add my favorite music to my personal blog, so I found a workaround. I directly simulate an event, when the mouse clicks anywhere on the webpage, it will automatically trigger 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 paused, play
}
}
setInterval("toggleSound()",1);
</script>
After handling it this way, when inserting audio, clicking anywhere on the webpage will trigger the playback effect. However, there are pros and cons to everything. By doing this, once the playback is started, the pause function cannot be used, which means it will keep playing.
If it is for writing a personal blog like mine, this drawback doesn't have a big impact. I'll record this method here.