原生html标签音视频预览

38 阅读1分钟

使用audio标签和video标签实现音频/视频预览,timeInSeconds设置起始播放时间,autoPlay设置自动播放。

<audio> 标签支持的文件格式:

  • MP3 (audio/mpeg)
  • WAV (audio/wav)
  • OGG (audio/ogg)
  • AAC (audio/aac)

<video> 标签支持的文件格式:

  • MP4 (video/mp4)
  • WebM (video/webm)
  • OGV (video/ogg)

audio

function AudioAndVideo(props) {
  // const { type, url, timeInSeconds } = props;
  const type = 'audio'
  const url = "https://amis.bj.bcebos.com/amis/2019-7/1562137295708/chicane-poppiholla-original-radio-edit%20(1).mp3"
  // const url =
    'https://amis.bj.bcebos.com/amis/2019-12/1577157317579/trailer_hd.mp4'
  const timeInSeconds = 0
  const videoRef = useRef(null)
  const audioRef = useRef(null)

  // 音视频定位,如果需要从指定时间开始播放的话
  useEffect(() => { 
    const secondsTime = timeInSeconds / 1000
    if (type === 'audio' && audioRef.current) {
      audioRef.current.currentTime = secondsTime
    }
    if (type === 'video' && videoRef.current) {
      videoRef.current.currentTime = secondsTime
    }
  }, [type, timeInSeconds])

  return (
    <div>
      {type === 'audio' ? (
        <audio
          ref={audioRef}
          controls
          autoPlay
          controlsList="nodownload"
          style={{ width: '100%' }}
        >
          <track kind="captions" />
          <source src={url} type="audio/mpeg" />
        </audio>
      ) : (
        <video
          ref={videoRef}
          controls
          muted
          autoPlay
          controlsList="nodownload"
          style={{ width: '100%' }}
        >
          <track kind="captions" />
          <source src={url} type="video/mp4" />
        </video>
      )}
    </div>
  )
}