Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > Web программирование > JavaScript, Ajax
Регистрация

Восстановить пароль

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 05.08.2025, 02:15   #1
Llirik1
Пользователь
 
Аватар для Llirik1
 
Регистрация: 03.03.2023
Сообщений: 63
По умолчанию Воспроизведение Аудио в JavaScript

Как остановить трек?

<script>
function soundClick() {
if (TrackMusicPlay == 1) { // никогда не будет равен 0! Как прировнять 0?
audio.stop(); // это его остановит?
} else {
var audio = new Audio(); // Создаём новый элемент Audio
audio.src = 'музыка.mp3'; // Указываем путь к звуку "клика"
audio.autoplay = true; // Автоматически запускаем
var TrackMusicPlay = 1;
}
}
</script>
Пароль: 'пароль'
Llirik1 вне форума Ответить с цитированием
Старый 05.08.2025, 03:02   #2
Llirik1
Пользователь
 
Аватар для Llirik1
 
Регистрация: 03.03.2023
Сообщений: 63
По умолчанию

<audio id="player" src="музыка.mp3"></audio>
<img src="play.png" width="50px" height="50px" onclick="document.getElementById('p layer').play()"><img src="pause.png" width="50px" height="50px" onclick="document.getElementById('p layer').pause()">
Пароль: 'пароль'
Llirik1 вне форума Ответить с цитированием
Старый 06.08.2025, 18:55   #3
uberchel
Участник клуба
 
Аватар для uberchel
 
Регистрация: 19.01.2009
Сообщений: 1,491
По умолчанию

Цитата:
Сообщение от Llirik1 Посмотреть сообщение
<img src="play.png" width="50px" height="50px" onclick="document.getElementById('p layer').play()"><img src="pause.png" width="50px" height="50px" onclick="document.getElementById('p layer').pause()">
Давным давно, изобрели такую штуку как бб коды! Для вставки и подсветки синтаксиса, тут есть к нопка [CODE]...
uberchel вне форума Ответить с цитированием
Старый 09.08.2025, 19:47   #4
Llirik1
Пользователь
 
Аватар для Llirik1
 
Регистрация: 03.03.2023
Сообщений: 63
По умолчанию

Код:
<audio id="player" src="музыка.mp3"></audio>
<img src="play.png" width="50px" height="50px" onclick="document.getElementById('p layer').play()"><img src="pause.png" width="50px" height="50px" onclick="document.getElementById('p layer').pause()">
Пробую бб коды)
Пароль: 'пароль'
Llirik1 вне форума Ответить с цитированием
Старый Вчера, 07:56   #5
uberchel
Участник клуба
 
Аватар для uberchel
 
Регистрация: 19.01.2009
Сообщений: 1,491
По умолчанию

Накидал пример, доработаешь под себя.

Код:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example audio</title>
    <style>
        .audio-player {
            width: 300px;
            height: 50px;
            background-color: #f0f0f0;
            border-radius: 10px;
            position: relative;
            user-select: none;
        }
        .audio-player__play-pause {
            width: 30px;
            height: 30px;
            background-color: #a29999;
            border-radius: 10px;
            position: absolute;
            bottom: 5px;
            left: 5px;
            cursor: pointer;
            text-align: center;
            line-height: 30px;
            color: #074a11;
        }

        .audio-player__progress {
            height: 5px;
            background-color: #074a11;
            border-radius: 10px;
            position: absolute;
            top: 0;
            left: 0;
            cursor: pointer;
        } 
        
        .audio-player__progress-bar {
            height: 5px;
            background-color: #636763;
            border-radius: 10px;
            position: absolute;
            top: 5px;
            left: 5px;
            right: 5px;
            cursor: pointer;
        }

        .audio-player__time {
            width: 70px;
            height: 15px;
            background-color: #cec6c653;
            border-radius: 10px;
            position: absolute;
            bottom: 5px;
            right: 5px;
            text-align: center;
            line-height: 15px;
            color: #074a11;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <div class="audio-player">
        <div class="audio-player__play-pause"></div>
        <div class="audio-player__progress-bar">
            <div class="audio-player__progress"></div>
        </div>
        <div class="audio-player__time"></div>
    </div>
    <script>
        const audio = new Audio('1.mp3');
        const playPause = document.querySelector('.audio-player__play-pause');
        const progress = document.querySelector('.audio-player__progress');
        const time = document.querySelector('.audio-player__time');
        const progressBar = document.querySelector('.audio-player__progress-bar');

        const secToTime = (sec) => {
            const minutes = Math.floor(sec / 60);
            const seconds = Math.floor(sec % 60);
            return   `${minutes}:${seconds}`;
        }
        
        let loop = true; //True если хочешь что бы играла по кругу
        let isReady = false;
        let isPlaying = false;
        let totalTime = 0;

        audio.addEventListener('loadedmetadata', () => {
            isReady = true;
            totalTime = audio.duration;
            console.log('loadedmetadata');
        });

        audio.addEventListener('play', () => {
            isPlaying = true;
            playPause.textContent = '[]';
            console.log('play');
        });

        audio.addEventListener('pause', () => {
            isPlaying = false;
            playPause.textContent = '>';
            console.log('pause');
        });
         
        audio.addEventListener('ended', () => {
            if (loop) {
                audio.currentTime = 0;
                audio.play();
            }
        });

        audio.addEventListener('error', () => {
            console.log('error');
        }); 

        audio.addEventListener('timeupdate', () => {
            const currentTime = audio.currentTime;
            progress.style.width = `${currentTime / totalTime * 100}%`;
            time.textContent = `${secToTime(currentTime)} / ${secToTime(totalTime)}`;
        });

        playPause.addEventListener('click', () => {
            if (!isReady) return;
            if (isPlaying) {
                audio.pause();
            } else {
                audio.play();
            }
        });

        progressBar.addEventListener('click', (e) => {
            const progressWidth = e.clientX - progress.getBoundingClientRect().left;
            const progressTime = (progressWidth / progressBar.offsetWidth) * totalTime;
            audio.currentTime = progressTime;
        });

    </script>
</body>
</html>
uberchel вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Воспроизведение аудио через внутренний микрофон koljsch Мобильные ОС (Android, iOS, Windows Phone) 1 13.03.2014 15:28
Воспроизведение аудио tolmik Visual C++ 7 30.09.2011 14:47
Воспроизведение аудио файла при движение мышки marsius Общие вопросы Delphi 7 27.05.2010 18:53
Воспроизведение видео/аудио потоков Fainder Работа с сетью в Delphi 0 27.05.2008 13:43