index.tsx 1.8 KB

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