audio 音频标签自定义样式修改以及添加播放控制事件

本文介绍如何使用HTML、CSS和JavaScript实现自定义的音频播放器样式,并添加播放、暂停、进度控制等事件。通过CSS设置音频元素的外观,JavaScript监听并处理播放时间更新、播放结束等事件,实现进度条的实时更新和拖动调整播放位置的功能。

html 代码

<div class="audio-wrapper">
    <audio>
        <source src="Files/Audio/2017-08/e259d760-5f1a-4ae0-a838-34d237ea93cc.mp3" type="audio/mp3">
    </audio>
    <div class="audio-left">![](image/play.png)</div>
    <div class="audio-right">
        <p style="max-width: 536px;">Beta-B_Kan R. Gao.mp3</p>
        <div class="progress-bar-bg" id="progressBarBg"><span id="progressDot"></span>
            <div class="progress-bar" id="progressBar"></div>
        </div>
        <div class="audio-time"><span class="audio-length-current" id="audioCurTime">00:00</span><span class="audio-length-total">01:06</span></div>
    </div>
</div>


css 代码

.audio-wrapper {
    background-color: #fcfcfc;
    margin: 10px auto;
    max-width: 670px;
    height: 70px;
    border: 1px solid #e0e0e0;
}

.audio-left {
    float: left;
    text-align: center;
    width: 18%;
    height: 100%;
}

.audio-left img {
    width: 40px;
    position: relative;
    top: 15px;
    margin: 0;
    display: initial;   /* 解除与app的样式冲突 */
    cursor: pointer;
}

.audio-right {
    margin-right: 2%;
    float: right;
    width: 80%;
    height: 100%;
}

.audio-right p {
    font-size: 15px;
    height: 35%;
    margin: 8px 0;

    /* 歌曲名称只显示在一行,超出部分显示为省略号 */
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    max-width: 243px;   /* 要适配小屏幕手机,所以最大宽度先设小一点,后面js根据屏幕大小重新设置 */    
}

.progress-bar-bg {
    background-color: #d9d9d9;
    position: relative;
    height: 2px;
    cursor: pointer;
}

.progress-bar {
    background-color: #649fec;
    width: 0;
    height: 2px;
}

.progress-bar-bg span {
    content: " ";
    width: 10px;
    height: 10px;
    border-radius: 50%;
    -moz-border-radius: 50%;
    -webkit-border-radius: 50%;
    background-color: #3e87e8;
    position: absolute;
    left: 0;
    top: 50%;
    margin-top: -5px;
    margin-left: -5px;
    cursor: pointer;
}

.audio-time {
    overflow: hidden;
    margin-top: -1px;
}

.audio-length-total {
    float: right;
    font-size: 12px;
}

.audio-length-current {
    float: left;
    font-size: 12px;
}
 

js 代码

document.addEventListener('DOMContentLoaded', function () {
    // 设置音频文件名显示宽度
    var element = document.querySelector('.audio-right');
    var maxWidth = window.getComputedStyle(element, null).width;
    document.querySelector('.audio-right p').style.maxWidth = maxWidth;

    // 初始化音频控制事件
    initAudioEvent();
}, false);

function initAudioEvent() {
    var audio = document.getElementsByTagName('audio')[0];
    var audioPlayer = document.getElementById('audioPlayer');

    // 点击播放/暂停图片时,控制音乐的播放与暂停
    audioPlayer.addEventListener('click', function () {
        // 监听音频播放时间并更新进度条
        audio.addEventListener('timeupdate', function () {
            updateProgress(audio);
        }, false);

        // 监听播放完成事件
        audio.addEventListener('ended', function () {
            audioEnded();
        }, false);

        // 改变播放/暂停图片
        if (audio.paused) {
            // 开始播放当前点击的音频
            audio.play();
            audioPlayer.src = './image/pause.png';
        } else {
            audio.pause();
            audioPlayer.src = './image/play.png';
        }
    }, false);

    // 点击进度条跳到指定点播放
    // PS:此处不要用click,否则下面的拖动进度点事件有可能在此处触发,此时e.offsetX的值非常小,会导致进度条弹回开始处(简直不能忍!!)
    var progressBarBg = document.getElementById('progressBarBg');
    progressBarBg.addEventListener('mousedown', function (event) {
        // 只有音乐开始播放后才可以调节,已经播放过但暂停了的也可以
        if (!audio.paused || audio.currentTime != 0) {
            var pgsWidth = parseFloat(window.getComputedStyle(progressBarBg, null).width.replace('px', ''));
            var rate = event.offsetX / pgsWidth;
            audio.currentTime = audio.duration * rate;
            updateProgress(audio);
        }
    }, false);

    // 拖动进度点调节进度
    dragProgressDotEvent(audio);
}

/**
 * 鼠标拖动进度点时可以调节进度
 * @param {*} audio
 */
function dragProgressDotEvent(audio) {
    var dot = document.getElementById('progressDot');

    var position = {
        oriOffestLeft: 0, // 移动开始时进度条的点距离进度条的偏移值
        oriX: 0, // 移动开始时的x坐标
        maxLeft: 0, // 向左最大可拖动距离
        maxRight: 0 // 向右最大可拖动距离
    };
    var flag = false; // 标记是否拖动开始

    // 鼠标按下时
    dot.addEventListener('mousedown', down, false);
    dot.addEventListener('touchstart', down, false);

    // 开始拖动
    document.addEventListener('mousemove', move, false);
    document.addEventListener('touchmove', move, false);

    // 拖动结束
    document.addEventListener('mouseup', end, false);
    document.addEventListener('touchend', end, false);

    function down(event) {
        if (!audio.paused || audio.currentTime != 0) { // 只有音乐开始播放后才可以调节,已经播放过但暂停了的也可以
            flag = true;

            position.oriOffestLeft = dot.offsetLeft;
            position.oriX = event.touches ? event.touches[0].clientX : event.clientX; // 要同时适配mousedown和touchstart事件
            position.maxLeft = position.oriOffestLeft; // 向左最大可拖动距离
            position.maxRight = document.getElementById('progressBarBg').offsetWidth - position.oriOffestLeft; // 向右最大可拖动距离

            // 禁止默认事件(避免鼠标拖拽进度点的时候选中文字)
            if (event && event.preventDefault) {
                event.preventDefault();
            } else {
                event.returnValue = false;
            }

            // 禁止事件冒泡
            if (event && event.stopPropagation) {
                event.stopPropagation();
            } else {
                window.event.cancelBubble = true;
            }
        }
    }

    function move(event) {
        if (flag) {
            var clientX = event.touches ? event.touches[0].clientX : event.clientX; // 要同时适配mousemove和touchmove事件
            var length = clientX - position.oriX;
            if (length > position.maxRight) {
                length = position.maxRight;
            } else if (length < -position.maxLeft) {
                length = -position.maxLeft;
            }
            var progressBarBg = document.getElementById('progressBarBg');
            var pgsWidth = parseFloat(window.getComputedStyle(progressBarBg, null).width.replace('px', ''));
            var rate = (position.oriOffestLeft + length) / pgsWidth;
            audio.currentTime = audio.duration * rate;
            updateProgress(audio);
        }
    }

    function end() {
        flag = false;
    }
}

/**
 * 更新进度条与当前播放时间
 * @param {object} audio - audio对象
 */
function updateProgress(audio) {
    var value = audio.currentTime / audio.duration;
    document.getElementById('progressBar').style.width = value * 100 + '%';
    document.getElementById('progressDot').style.left = value * 100 + '%';
    document.getElementById('audioCurTime').innerText = transTime(audio.currentTime);
}

/**
 * 播放完成时把进度调回开始的位置
 */
function audioEnded() {
    document.getElementById('progressBar').style.width = 0;
    document.getElementById('progressDot').style.left = 0;
    document.getElementById('audioCurTime').innerText = transTime(0);
    document.getElementById('audioPlayer').src = './image/play.png';
}

/**
 * 音频播放时间换算
 * @param {number} value - 音频当前播放时间,单位秒
 */
function transTime(value) {
    var time = "";
    var h = parseInt(value / 3600);
    value %= 3600;
    var m = parseInt(value / 60);
    var s = parseInt(value % 60);
    if (h > 0) {
        time = formatTime(h + ":" + m + ":" + s);
    } else {
        time = formatTime(m + ":" + s);
    }

    return time;
}

/**
 * 格式化时间显示,补零对齐
 * eg:2:4  -->  02:04
 * @param {string} value - 形如 h:m:s 的字符串 
 */
function formatTime(value) {
    var time = "";
    var s = value.split(':');
    var i = 0;
    for (; i < s.length - 1; i++) {
        time += s[i].length == 1 ? ("0" + s[i]) : s[i];
        time += ":";
    }
    time += s[i].length == 1 ? ("0" + s[i]) : s[i];

    return time;
}
 

<think>我们正在讨论如何在React中实现自定义音频播放器。根据引用内容,我们可以知道: 1. 需要创建一个音频播放器组件(引用[1]) 2. 可以利用HTML5的`<audio>`标签(引用[2]) 3. 需要处理播放、暂停等功能,并且确保同时只播放一个音频(引用[1]) 4. 可以使用React状态和事件处理来控制音频 步骤: 1. 创建组件:创建一个React组件来封装音频播放器。 2. 使用`<audio>`标签:在组件中使用HTML5的`<audio>`元素。 3. 状态管理:使用React的`useState`来管理播放状态(是否正在播放)和当前音频源。 4. 控制播放:提供播放、暂停等方法,并绑定到按钮上。 5. 多个音频控制:为了确保同时只播放一个音频,我们可以维护一个全局状态(例如使用Context)或者在上层组件中控制当前播放音频。 由于用户要求自定义,我们可以设计一个简单的播放器,具有播放/暂停按钮、进度条和音量控制等。但根据引用,我们首先实现基本功能。 基本实现思路: - 组件接收一个`src`属性,表示音频源。 - 使用`useRef`来获取`<audio>`元素的DOM节点,以便直接控制播放和暂停。 - 使用状态`isPlaying`来跟踪当前是否在播放。 代码示例: ```jsx import React, { useState, useRef } from 'react'; const AudioPlayer = ({ src }) => { const [isPlaying, setIsPlaying] = useState(false); const audioRef = useRef(null); const togglePlayPause = () => { if (isPlaying) { audioRef.current.pause(); } else { audioRef.current.play(); } setIsPlaying(!isPlaying); }; return ( <div> <audio ref={audioRef} src={src} onEnded={() => setIsPlaying(false)} /> <button onClick={togglePlayPause}> {isPlaying ? '暂停' : '播放'} </button> </div> ); }; export default AudioPlayer; ``` 但是,为了确保在播放一个音频时暂停其他音频,我们可以考虑在父组件中管理当前播放音频ID(或索引)。当播放一个音频时,将当前播放的ID设置为该音频,并暂停之前播放音频。 改进方案(在父组件中管理): 1. 父组件维护一个`currentPlayingId`状态,用于记录当前正在播放音频ID。 2. 将`setCurrentPlayingId`方法传递给每个`AudioPlayer`组件。 3. 在`AudioPlayer`组件中,当点击播放时,调用父组件传递的方法设置当前播放ID,同时如果之前有播放音频,父组件会暂停它(通过ref调用暂停)。 或者,我们可以将音频控制逻辑提升到父组件,子组件只负责触发事件。 另一种方法是使用Context来管理全局的音频状态,但这里我们先使用父组件管理的方式。 假设我们有一个音频列表,每个音频有一个id: ```jsx // 父组件 import React, { useState, useRef } from 'react'; import AudioPlayer from './AudioPlayer'; const AudioList = () => { // 当前正在播放音频id const [currentPlayingId, setCurrentPlayingId] = useState(null); // 存储每个音频的ref,用于暂停 const audioRefs = useRef({}); const handlePlay = (id) => { // 如果之前有播放音频,暂停它 if (currentPlayingId && currentPlayingId !== id) { const prevAudio = audioRefs.current[currentPlayingId]; prevAudio.pause(); } // 设置当前播放的id setCurrentPlayingId(id); }; // 音频列表数据 const audioList = [ { id: 1, src: 'audio1.mp3' }, { id: 2, src: 'audio2.mp3' }, // ... 其他音频 ]; return ( <div> {audioList.map(audio => ( <AudioPlayer key={audio.id} id={audio.id} src={audio.src} isPlaying={currentPlayingId === audio.id} onPlay={handlePlay} ref={(el) => audioRefs.current[audio.id] = el} // 将每个AudioPlayer内部的audio元素ref暴露给父组件 /> ))} </div> ); }; ``` 然后修改`AudioPlayer`组件,使其能够接收`isPlaying`和`onPlay`属性,并且将内部的audio元素ref通过父组件传递的ref回调暴露出去。 但是,直接暴露audio元素给父组件可能不是最佳实践,我们可以使用`forwardRef`和`useImperativeHandle`来暴露播放和暂停方法。 修改后的`AudioPlayer`组件: ```jsx import React, { forwardRef, useImperativeHandle, useState } from 'react'; const AudioPlayer = forwardRef(({ id, src, isPlaying, onPlay }, ref) => { const [internalIsPlaying, setInternalIsPlaying] = useState(false); const audioRef = useRef(null); // 暴露播放和暂停方法给父组件 useImperativeHandle(ref, () => ({ play: () => { audioRef.current.play(); setInternalIsPlaying(true); }, pause: () => { audioRef.current.pause(); setInternalIsPlaying(false); }, })); // 当父组件传递的isPlaying状态变化时,需要同步内部状态(但注意,父组件可能通过ref控制,所以这里可能需要同步) // 但是,我们这里主要让父组件控制暂停,播放还是由组件内部触发(因为用户点击播放按钮) const togglePlayPause = () => { if (isPlaying) { // 如果当前正在播放(即当前播放的是这个音频),则暂停 audioRef.current.pause(); setInternalIsPlaying(false); onPlay(null); // 告诉父组件没有播放的了,或者父组件自己会处理? } else { // 播放这个音频 onPlay(id); // 通知父组件播放这个id的音频 audioRef.current.play(); setInternalIsPlaying(true); } }; // 注意:我们这里同时使用父组件的isPlaying和内部状态,可能会冲突。所以我们可以完全由父组件控制,或者完全由内部状态控制。 // 但是,父组件暂停其他音频时,会调用这个组件的pause方法,从而改变内部状态。所以这里我们让内部状态和父组件的isPlaying保持一致? // 实际上,我们让父组件的currentPlayingId和这个组件的isPlaying状态同步:当父组件设置这个组件的isPlaying为false时(因为播放了别的音频),我们需要暂停并更新内部状态。 // 使用一个useEffect来同步父组件的isPlaying和内部状态 useEffect(() => { if (isPlaying) { // 父组件要求播放(但这种情况不会发生,因为播放是由子组件触发的) // 所以这里我们只处理暂停的情况:当父组件设置isPlaying为false,而内部状态为true时,需要暂停 if (internalIsPlaying) { audioRef.current.pause(); setInternalIsPlaying(false); } } }, [isPlaying]); return ( <div> <audio ref={audioRef} src={src} onEnded={() => setInternalIsPlaying(false)} /> <button onClick={togglePlayPause}> {internalIsPlaying ? '暂停' : '播放'} </button> </div> ); }); export default AudioPlayer; ``` 但是,上面的实现比较复杂,容易造成状态混乱。更简单的方式是:父组件只负责暂停之前播放音频,而每个音频组件的播放状态由自己管理,但播放时通知父组件,父组件会暂停其他音频(通过ref调用其他组件的pause方法)。 因此,我们调整父组件: ```jsx // 父组件 import React, { useState, useRef } from 'react'; import AudioPlayer from './AudioPlayer'; const AudioList = () => { // 存储每个音频组件的ref,以便调用其pause方法 const playerRefs = useRef({}); const handlePlay = (id) => { // 遍历所有ref,如果id不是当前播放的,则暂停 Object.keys(playerRefs.current).forEach(playerId => { if (playerId !== id) { const player = playerRefs.current[playerId]; if (player) { player.pause(); } } }); }; const audioList = [ { id: '1', src: 'audio1.mp3' }, { id: '2', src: 'audio2.mp3' }, ]; return ( <div> {audioList.map(audio => ( <AudioPlayer key={audio.id} id={audio.id} src={audio.src} onPlay={handlePlay} ref={(el) => { playerRefs.current[audio.id] = el; // 存储每个组件的ref }} /> ))} </div> ); }; ``` 然后,修改`AudioPlayer`组件,使用`forwardRef`来暴露一个`pause`方法: ```jsx import React, { forwardRef, useState, useRef, useImperativeHandle } from 'react'; const AudioPlayer = forwardRef(({ id, src, onPlay }, ref) => { const [isPlaying, setIsPlaying] = useState(false); const audioRef = useRef(null); useImperativeHandle(ref, () => ({ pause: () => { if (isPlaying) { audioRef.current.pause(); setIsPlaying(false); } } })); const togglePlayPause = () => { if (isPlaying) { audioRef.current.pause(); setIsPlaying(false); } else { // 播放前先通知父组件,父组件会暂停其他所有音频 onPlay(id); audioRef.current.play(); setIsPlaying(true); } }; return ( <div> <audio ref={audioRef} src={src} onEnded={() => setIsPlaying(false)} /> <button onClick={togglePlayPause}> {isPlaying ? '暂停' : '播放'} </button> </div> ); }); export default AudioPlayer; ``` 这样,当点击一个音频播放按钮时,它会通知父组件,父组件会暂停其他所有音频(通过调用它们的pause方法)。同时,每个音频组件自己管理播放状态。 以上是一个基本实现。根据引用[3][4],我们还可以添加更多功能,比如进度条、音量控制等,但用户问题主要集中在如何实现基本播放和暂停,以及多个音频同时只播放一个。 因此,我们提供以上实现作为基础。 §§相关问题§§ 1. 如何在React音频播放器中实现进度条控制? 2. 如何为React音频播放添加音量调节功能? 3. React音频播放器如何实现跨组件状态共享(例如全局播放状态)? 4. 如何优化React音频播放器的性能以避免不必要的渲染?</think>### React 自定义音频播放器实现方法 在 React 中实现自定义音频播放器需要结合 HTML5 `<audio>` 元素和 React 的状态管理机制。以下是分步实现方法: #### 1. **创建基础音频组件** ```jsx import React, { useState, useRef } from 'react'; const AudioPlayer = ({ src }) => { const [isPlaying, setIsPlaying] = useState(false); const [currentTime, setCurrentTime] = useState(0); const audioRef = useRef(null); // 播放/暂停控制 const togglePlayPause = () => { if (isPlaying) { audioRef.current.pause(); } else { audioRef.current.play(); } setIsPlaying(!isPlaying); }; // 时间更新处理 const handleTimeUpdate = () => { setCurrentTime(audioRef.current.currentTime); }; return ( <div className="audio-player"> <audio ref={audioRef} src={src} onTimeUpdate={handleTimeUpdate} onEnded={() => setIsPlaying(false)} /> <button onClick={togglePlayPause}> {isPlaying ? '暂停' : '播放'} </button> <input type="range" min="0" max={audioRef.current?.duration || 100} value={currentTime} onChange={(e) => { audioRef.current.currentTime = e.target.value; setCurrentTime(e.target.value); }} /> </div> ); }; export default AudioPlayer; ``` #### 2. **实现多音频互斥播放** 通过全局状态管理确保同时只播放一个音频: ```jsx // 上下文组件 AudioContext.js import React, { createContext, useState, useContext } from 'react'; const AudioContext = createContext(); export const AudioProvider = ({ children }) => { const [currentAudioId, setCurrentAudioId] = useState(null); return ( <AudioContext.Provider value={{ currentAudioId, setCurrentAudioId }}> {children} </AudioContext.Provider> ); }; export const useAudioContext = () => useContext(AudioContext); ``` 在音频组件中使用: ```jsx const { currentAudioId, setCurrentAudioId } = useAudioContext(); const togglePlayPause = () => { if (currentAudioId !== id && currentAudioId) { // 暂停其他音频 document.getElementById(`audio-${currentAudioId}`)?.pause(); } if (isPlaying) { audioRef.current.pause(); setCurrentAudioId(null); } else { audioRef.current.play(); setCurrentAudioId(id); } setIsPlaying(!isPlaying); }; ``` #### 3. **添加高级功能** ```jsx // 音量控制 const [volume, setVolume] = useState(1); const handleVolumeChange = (e) => { const newVolume = parseFloat(e.target.value); audioRef.current.volume = newVolume; setVolume(newVolume); }; // 进度条跳转 const handleSeek = (e) => { const newTime = parseFloat(e.target.value); audioRef.current.currentTime = newTime; setCurrentTime(newTime); }; // 渲染部分 <input type="range" min="0" max="1" step="0.01" value={volume} onChange={handleVolumeChange} /> ``` #### 4. **完整组件集成** ```jsx import React, { useState, useRef, useEffect } from 'react'; import { useAudioContext } from './AudioContext'; const CustomAudioPlayer = ({ id, src }) => { const [isPlaying, setIsPlaying] = useState(false); const [currentTime, setCurrentTime] = useState(0); const [duration, setDuration] = useState(0); const [volume, setVolume] = useState(0.7); const audioRef = useRef(null); const { currentAudioId, setCurrentAudioId } = useAudioContext(); useEffect(() => { const audio = audioRef.current; const updateData = () => setDuration(audio.duration); audio.addEventListener('loadedmetadata', updateData); return () => audio.removeEventListener('loadedmetadata', updateData); }, []); const togglePlayPause = () => { if (currentAudioId !== id && currentAudioId) { document.getElementById(`audio-${currentAudioId}`)?.pause(); } if (isPlaying) { audioRef.current.pause(); setCurrentAudioId(null); } else { audioRef.current.play(); setCurrentAudioId(id); } setIsPlaying(!isPlaying); }; return ( <div className="custom-audio"> <audio id={`audio-${id}`} ref={audioRef} src={src} volume={volume} onTimeUpdate={() => setCurrentTime(audioRef.current.currentTime)} onEnded={() => { setIsPlaying(false); setCurrentAudioId(null); }} /> <div className="controls"> <button onClick={togglePlayPause}> {isPlaying ? '⏸' : '▶'} </button> <input type="range" min="0" max={duration} value={currentTime} onChange={(e) => { audioRef.current.currentTime = e.target.value; setCurrentTime(e.target.value); }} /> <input type="range" min="0" max="1" step="0.01" value={volume} onChange={(e) => { audioRef.current.volume = e.target.value; setVolume(e.target.value); }} /> </div> </div> ); }; ``` #### 5. **样式优化建议** ```css .custom-audio { display: flex; align-items: center; padding: 10px; background: #f5f5f5; border-radius: 8px; } .controls { display: flex; gap: 15px; width: 100%; } input[type="range"] { width: 100%; } ``` ### 关键实现要点 1. **使用 ref 直接操作 DOM**:通过 `useRef` 获取 `<audio>` 元素实例 2. **状态同步**:利用 `onTimeUpdate` 事件同步播放进度 3. **全局状态管理**:使用 Context API 实现多音频互斥控制 4. **事件绑定**:处理播放结束、元数据加载等关键事件 5. **自定义控制**:通过 React 状态绑定实现进度条、音量控制 这种方法提供了高度可定制的音频播放器,可根据需求扩展播放列表、循环模式、倍速播放等功能[^1][^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值