feat(audio): 改进音频自动播放逻辑

- 在HTML中将音频preload属性从none改为auto
- 添加用户交互检测以提高自动播放成功率
- 使用setTimeout延迟播放尝试以绕过浏览器限制
- 移除不必要的console.error输出
- 优化CSS以确保评论头像正确显示
This commit is contained in:
hehh
2025-11-30 18:27:31 +08:00
parent a871a734ee
commit 67b7c0e5f9
3 changed files with 17 additions and 11 deletions

View File

@@ -301,7 +301,7 @@
<button id="fab-music" class="fab-item" tabindex="0"><i class="ri-music-2-line"></i><span class="fab-text">Play</span></button>
</div>
</div>
<audio id="site-audio" class="site-audio" src="data/至少做一件离谱的事-Kiri T_compressed.mp3" loop preload="none"></audio>
<audio id="site-audio" class="site-audio" src="data/至少做一件离谱的事-Kiri T_compressed.mp3" autoplay loop preload="auto"></audio>
</main>
<!-- 微信弹窗 -->

View File

@@ -450,6 +450,12 @@
height: 28px !important;
object-fit: cover; /* 修复移动端头像拉伸问题 */
}
.atk-comment>.atk-avatar img {
object-fit: cover;
object-position: center;
width: 28px !important;
height: 28px !important;
}
.atk-meta {
font-size: 12px !important;

View File

@@ -1133,22 +1133,22 @@ class UIManager {
const shouldRemainPaused = this.shouldMusicRemainPaused();
// 如果不应该保持暂停状态,则尝试播放
if (!shouldRemainPaused) {
this.audio.autoplay = true;
let userInteracted = true;
this.audio.play().catch(() => {
// 静默处理播放失败
userInteracted = false;
});
// 添加用户交互检查,避免浏览器阻止自动播放
const attemptAutoplay = () => {
// 检查是否已有用户交互
if (this.userInteracted) {
this.audio.play().catch(() => {
// 静默处理播放失败
console.error('Failed to play audio.');
});
} else {
if (this.userInteracted === false) {
// 添加一次性用户交互监听器
const enableAudio = () => {
this.userInteracted = true;
setTimeout(() => {
this.audio.play().catch(() => {
console.error('Failed to play audio.');
});
}, 1000);
document.removeEventListener('click', enableAudio);
document.removeEventListener('touchstart', enableAudio);
document.removeEventListener('keydown', enableAudio);