Next.js Discord

Discord Forum

Caching audio in nextjs

Unanswered
aa55h posted this in #help-forum
Open in Discord
hi im having this audio thingy here, but it always takes some time to load, how can i cache it so its faster?

12 Replies

🤔 why would you need this approach for playing audio?
@James4u 🤔 why would you need this approach for playing audio?
how else do i play audio?
can't you use native audio tag?
@James4u can't you use native audio tag?
I want to play the audio more than once at a time
Would that work?
@aa55h I want to play the audio more than once at a time
do you need to auto play the audios btw?
@aa55h I want to play the audio more than once at a time
did you mean playing multiple audios at once?
yeah it should be possible
@James4u did you mean playing multiple audios at once?
I want to play the audio on click, which means multiple of them would play at once
import { useRef } from 'react';

export default function MultiAudioPlayer() {
  // Define refs for each audio element
  const audioRefs = useRef([]);

  // List of audio file URLs
  const audioFiles = [
    '/audio1.mp3',
    '/audio2.mp3',
    '/audio3.mp3'
  ];

  // Function to play all audio files at once
  const playAllAudios = () => {
    audioRefs.current.forEach((audio) => {
      if (audio) {
        audio.currentTime = 0; // Reset playback if needed
        audio.play();
      }
    });
  };

  return (
    <div>
      {/* Render audio elements and set refs */}
      {audioFiles.map((file, index) => (
        <audio
          key={index}
          src={file}
          ref={(el) => (audioRefs.current[index] = el)}
          preload="auto"
        />
      ))}
      <button onClick={playAllAudios}>Play All Audios</button>
    </div>
  );
}

Try this out