index.tsx 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { Image, Video, VideoProps } from "@tarojs/components";
  2. // import style from "../index.module.less";
  3. import { useEffect, useRef } from "react";
  4. import Taro from "@tarojs/taro";
  5. interface Props {
  6. source: string;
  7. className: string;
  8. }
  9. export const AvatarMedia = ({ source, className }: Props) => {
  10. const videoRef = useRef<React.ComponentType<VideoProps>|null>(null);
  11. const videoContext = useRef<Taro.VideoContext|null>(null);
  12. const videoId = useRef(`video-${Math.random().toString(36).substr(2, 9)}`);
  13. const videoErrorCallback = (e) => {
  14. console.log('Video error info:')
  15. console.log(e.detail)
  16. }
  17. // 处理 ios 上无法循环播放的 bug
  18. const handleOnEnded = () => {
  19. if(videoContext.current){
  20. videoContext.current.seek(0)
  21. videoContext.current.play()
  22. }
  23. }
  24. useEffect(() => {
  25. if (videoRef.current) {
  26. videoContext.current = Taro.createVideoContext(videoId.current, this);
  27. }
  28. }, []);
  29. if (source.lastIndexOf('.mp4') > -1) {
  30. return (
  31. <Video
  32. id={videoId.current}
  33. ref={videoRef}
  34. controls={false}
  35. showCenterPlayBtn={false}
  36. loop={true}
  37. muted={true}
  38. autoplay
  39. onEnded={handleOnEnded}
  40. objectFit="cover"
  41. className={className}
  42. onError={videoErrorCallback}
  43. // src="https://cdn.wehome.cn/cmn/mp4/3/META-H8UKWHWU-YAUTZH7ECGRDC57FD3NI3-CUGVCS8M-CD.mp4"
  44. src={source}
  45. />
  46. );
  47. }
  48. return (
  49. <Image
  50. mode="widthFix"
  51. className={className}
  52. src={source}
  53. />
  54. );
  55. };