在React中播放新音频时如何暂停之前的音频?

问题描述 投票:0回答:1

当我单击“PlayCircleFilled”图标时,音频播放完美,问题是,如果用户单击不同的“PlayCircleFilled”图标,所有音频都会同时播放。

我想要实现的是,当用户单击新的“PlayCircleFilled”图标时停止播放音频,以便一次只播放一个音频,播放最后单击的音频。

我的代码如下:

const Client = (props) => {

  const {
    sentence,
    typeConversation
  } = props;

  const [audioUrl, setAudioUrl] = useState(null);
  const audioRef = useRef(null);

  const handleAudioPlay = (url) => {
    if (audioRef.current) {
      audioRef.current.pause();
      audioRef.current.currentTime = 0;
    }
    setAudioUrl(url);
  };

  const handleAudioEnded = () => {
    setAudioUrl(null); 
  };

  const renderTextWithAudioPlayer = (text) => {
    const combinedRegex = /(https?:\/\/[^\s]+)|(\[Audio\])/g;
    const parts = text.split(combinedRegex).filter(part => part !== undefined && part !== "");

    let renderedElements = [];

    parts.forEach((part, index) => {
      if (/https?:\/\/[^\s]+/.test(part)) {
        const fileExtension = part.split('.').pop().toLowerCase();
        if (fileExtension === 'wav' || fileExtension === 'mp3' || fileExtension === 'ogg') {
          renderedElements.push(
            <Tooltip key={index} placement="bottom" title="Reproducir audio">
              <PlayCircleFilled className="play-audio-icon" onClick={() => handleAudioPlay(part)} />
            </Tooltip>
          );
        } else {
          renderedElements.push(
            <a key={index} href={part} target="_blank" rel="noopener noreferrer">
              {part}
            </a>
          );
        }
      } else if (/\[Audio\]/.test(part)) {
        renderedElements.push(<AudioFilled className="play-audio-icon" key={index} />);
      } else {
        renderedElements.push(<span key={index} dangerouslySetInnerHTML={{ __html: part }} />);
      }
    });
    return renderedElements;
  };

  return(
    <div className="chat-message" id={sentence.id}>
      <div className="chat-message__text">
      {
        typeConversation == 'audio' ?
        <h6 className="chat-message__title chat-message__title--client">
          Cliente | {sentence.start_time}
        </h6>
        :
        <h6 className="chat-message__title chat-message__title--client">
          Cliente | {sentence.date} {sentence.time}
        </h6>
      }
        <p>
          {renderTextWithAudioPlayer(sentence.text)}
        </p>
        {audioUrl && (
          <audio controls autoPlay ref={audioRef} onEnded={handleAudioEnded} style={{ display: 'none' }}>
            <source src={audioUrl} type="audio/mpeg" />
            Su navegador no admite la reproducción de audio.
          </audio>
        )}
      </div>
    </div>
  );
}

export default Client;

非常感谢您的宝贵时间,希望您能帮助我!

reactjs audio html5-audio
1个回答
0
投票

我们将讨论儿童手表的最新趋势以及现代一代如何使用它们。从 GPS 追踪到教育游戏,这些手表不仅为孩子们带来乐趣,也让父母安心 [了解更多 https://www.ruzaaffiliate.com/kids-watch-used-by-the-modern- Generation

© www.soinside.com 2019 - 2024. All rights reserved.