0

I'm refactoring a Reactjs app created using CRA to Vite.js. Fun.jsx, which plays an audio when it's mounted and stops when unmounted. However, after shifting to Vite, it doesn't play the. There were no issues before vite.

I had to change a couple lines to make vite happy, they are commented:

import React, { useEffect, useMemo } from 'react';
import { Hash, Sort, BinaryString } from './FunItems';
import Background from './Background';

// const musicContext = require.context('../assets/music/', false, /\.(aac)$/);
// const musicFiles = musicContext.keys().map(musicContext);

// for vite, use this instead:
const musicContext = import.meta.glob('../assets/music/*.aac');
const musicFiles = Object.keys(musicContext).map(key => musicContext[key]());

export default function Fun() {
  const randomSongIndex = Math.floor(Math.random() * musicFiles.length);
  const audio = useMemo(() => new Audio(musicFiles[randomSongIndex]), [randomSongIndex]);

  useEffect(() => {
    audio.loop = true;
    audio.volume = 0.3;

    let playing = audio.play();
    if (playing !== undefined) {
      playing.then(_ => {
      })
        .catch(error => {
          console.log(error);
        });
    }

    return () => audio.pause();
  }, [audio]);

  return (
    <div>
      <Background />
      <Hash />
      <Sort />
      <BinaryString />
    </div>
  );
}

Console shows: DOMException: play() failed because the user didn't interact with the document first. https : // goo . gl / xX8pDD (stackoverflow disallows googl links)

Didn't face the above problem before using Vite with the same code, what's the issue?

ransom
  • 173
  • 1
  • 9
  • Re that error: https://stackoverflow.com/questions/49930680/how-to-handle-uncaught-in-promise-domexception-play-failed-because-the-use – Andy Aug 04 '23 at 11:17

0 Answers0