Как запустить код после загрузки страницы?

В реакте новичок. Задача после того как страница загрузиться запустить код new Audio("../1.mp3").play();

Пробовал использовать useEffect, но видно я что-то сделал не правильно или не правильный хук выбрал. Помогите разобраться или сошлитесь, пожалуйста, на документацию


Ответы (1 шт):

Автор решения: Sire IMPACTUS

Вот код из одного моего проекта. Звук загружается сразу после загрузки скрипта. И воспроизводится при рендере.

ВАЖНО: звук должен лежать в папке public и путь у него будет примерно следующий (https://localhost:3000/1.mp3), иначе воспроизводится звук просто так не будет.

const sound = {
    v1: ".../audio"
};
const sendPath = sound.v1;
const sounds = {
    firstLoad: new Audio(sendPath)
};

type soundNames = 'firstLoad' | string;

export const playSound = (soundName: soundNames) => {
    if (sounds[soundName]) {
        sounds[soundName].pause();
        sounds[soundName].play();
    }
}
export const stopSound = (soundName: soundNames) => {
    if (sounds[soundName]) {
        sounds[soundName].pause();
    }
}
export const configureSound = (soundName: soundNames, newSoundName: string, processing: (clone?: HTMLAudioElement) => HTMLAudioElement): boolean => {
    if (sounds[soundName]) {
        const newNode = processing(sounds[soundName].cloneNode(true));
        if (newNode) {
            sounds[newSoundName] = newNode;
            return true;
        }
        return false;
    }
    return false;
}

// USE


const App() {
    useEffect(() => {
      playSound("firstLoad");
    }, []);

   return null;
}

→ Ссылка