嗨咿,我是 illumi,前天講到點擊觸發音效的,那今天來一起做一個。雖然現在網站比較不會放音樂,但像Awwwards上那種沈浸感的網站背景音樂,就會放背景音樂營造氛圍感。最簡單的方式就是用 HTML 的 <audio>
標籤:
<audio src="/music.mp3" autoplay loop controls></audio>
不過這樣會出現一個「很單調的瀏覽器預設播放器」,長相固定,也不好整合進網站的設計語言。
那要怎麼做出更漂亮、客製化的背景音樂控制器呢?
<audio>
播放音樂:隱藏掉預設的控制介面(不加 controls
)。import { useEffect, useRef, useState } from "react";
export default function AudioController() {
const audioRef = useRef<HTMLAudioElement>(null);
const [isPlaying, setIsPlaying] = useState(true);
// 切換播放狀態
const toggleAudio = () => {
if (!audioRef.current) return;
if (isPlaying) {
audioRef.current.pause();
setIsPlaying(false);
} else {
audioRef.current.play();
setIsPlaying(true);
}
};
// 初始化設定
useEffect(() => {
if (audioRef.current) {
audioRef.current.volume = 0.6; // 預設音量
audioRef.current.play().catch(() => {
// 部分瀏覽器不允許自動播放 → 停在暫停狀態
setIsPlaying(false);
});
}
}, []);
return (
<>
{/* 背景音樂,沒有 controls */}
<audio ref={audioRef} src="/sounds/gameRoom.mp3" loop autoPlay />
{/* 自訂按鈕 */}
<buttononClick={toggleAudio}
className="fixed bottom-5 left-5 flex gap-1 cursor-pointer z-50"
>
{[...Array(3)].map((_, i) => (
<spankey={i}
className={`w-1 h-7 bg-schema-primary rounded-sm ${
isPlaying ? "animate-wave" : ""
}`}
style={{
animationDelay: `${i * 0.2}s`,
}}
/>
))}
</button>
</>
);
}
這裡用了三條小柱狀條,播放時會加上 animate-wave
動畫,看起來像「音樂在律動」,比原生播放器有趣多了。
再在css中加入動畫效果:
.animate-wave {
animation: wave 1s infinite ease-in-out;
}
效果就出來啦~快去試試吧!或是做過什麼酷酷播放按鈕也可以留言~我們明天見~