iT邦幫忙

2025 iThome 鐵人賽

DAY 9
0
Modern Web

在Vibe Coding 時代一起來做沒有AI感的漂亮網站吧!系列 第 9

就是要霸佔你的喇叭!一起做背景音樂播放器吧~

  • 分享至 

  • xImage
  •  

嗨咿,我是 illumi,前天講到點擊觸發音效的,那今天來一起做一個。雖然現在網站比較不會放音樂,但像Awwwards上那種沈浸感的網站背景音樂,就會放背景音樂營造氛圍感。最簡單的方式就是用 HTML 的 <audio> 標籤:

<audio src="/music.mp3" autoplay loop controls></audio>

https://ithelp.ithome.com.tw/upload/images/20250910/20178506qNRC9ffVrf.png

不過這樣會出現一個「很單調的瀏覽器預設播放器」,長相固定,也不好整合進網站的設計語言。

那要怎麼做出更漂亮、客製化的背景音樂控制器呢?


核心思路

  1. <audio> 播放音樂:隱藏掉預設的控制介面(不加 controls)。
  2. 用 JavaScript/React 控制播放狀態:可以 play / pause、調整音量。
  3. 自訂 UI:做一個動畫小按鈕,顯示「正在播放 / 已暫停」。

範例程式(React + Tailwind)

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;
}

Yes
效果就出來啦~快去試試吧!或是做過什麼酷酷播放按鈕也可以留言~我們明天見~


上一篇
不用寫程式get 液態玻璃效果、3D世界,香香React元件庫!
系列文
在Vibe Coding 時代一起來做沒有AI感的漂亮網站吧!9
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言