https://www.w3schools.com/jsref/dom_obj_audio.asp
HTML DOM Audio Object
Audio Object
| The Audio object represents an HTML <audio> element. Access an Audio Object You can access an <audio> element by using getElementById(): | Audio Object представляет элемент HTML Доступ к Audio Object Вы можете получить доступ к элементу |
var x = document.getElementById("myAudio");
| Create an Audio Object You can create an <audio> element by using the document.createElement() method: | Создать аудио объект Вы можете создать элемент |
Audio Object Properties — Свойства аудио объекта
var x = document.getElementById("myAudio");
Audio Object Properties
| Property | Description | |
|---|---|---|
| audioTracks — НЕ поддерживается. | Returns an AudioTrackList object representing available audio tracks | Возвращает объект AudioTrackList, представляющий доступные аудиодорожки. |
| autoplay | Sets or returns whether the audio should start playing as soon as it is ready | Устанавливает или возвращает, должно ли аудио начинать воспроизводиться сразу после готовности |
| buffered | Returns a TimeRanges object representing the buffered parts of an audio | Возвращает объект TimeRanges, представляющий буферизованные части аудио |
| controller | Returns the MediaController object representing the current media controller of an audio | Возвращает объект MediaController, представляющий текущий медиа-контроллер аудио. |
| controls | Sets or returns whether an audio should have controls displayed (play/pause etc) | Устанавливает или возвращает, должны ли отображаться элементы управления аудио (воспроизведение/пауза и т. д.) |
| crossOrigin | Sets or returns the CORS settings of an audio | Устанавливает или возвращает настройки CORS аудио |
| currentSrc | Returns the URL of the current audio | Возвращает URL текущего аудио |
| currentTime | Sets or returns the current playback position in an audio (in seconds) | Устанавливает или возвращает текущую позицию воспроизведения в аудио (в секундах) |
| defaultMuted | Sets or returns whether the audio should be muted by default | Устанавливает или возвращает значение, следует ли отключать звук по умолчанию. |
| defaultPlaybackRate | Sets or returns whether the default playback speed of the audio | Устанавливает или возвращает значение скорости воспроизведения звука по умолчанию. |
| duration | Returns the length of an audio(in seconds) | Возвращает длительность аудио (в секундах) |
| ended | Returns whether the playback of the audio has ended | Returns whether the playback of the audio has ended |
| error | Returns a MediaError object representing the error state of the audio | Возвращает объект MediaError, представляющий состояние ошибки аудио. |
| loop | Sets or returns whether the audio should start playing over again, every time it is finished | Устанавливает или возвращает, должно ли воспроизведение звука начинаться заново каждый раз после его завершения |
| mediaGroup | Sets or returns the name of the media group the audio(s) is a part of | Устанавливает или возвращает имя медиагруппы, частью которой является аудио (браузеры так и не внедрили эту функциональность.) Внизу пример как управлять двумя плеерами одновременно посредством JS. |
| muted | Sets or returns whether the sound should be turned off | Звук включен или выключен. |
| networkState | Returns the current network state of an audio | |
| paused | Returns whether an audio is paused | |
| playbackRate | Sets or returns the speed of the audio playback | |
| played | Returns a TimeRanges object representing the played parts of the audio | |
| preload | Sets or returns the value of the preload attribute of an audio | |
| readyState | Returns the current ready state of an audio | |
| seekable | Returns a TimeRanges object representing the seekable parts of an audio | |
| seeking | Returns whether the user is currently seeking in the audio | |
| src | Sets or returns the value of the src attribute of an audio | |
| textTracks | Returns a TextTrackList object representing the available text tracks | |
| volume | Sets or returns the audio volume of an audio |
Audio Object Methods
| Method | Description |
|---|---|
| addTextTrack() | Adds a new text track to the audio |
| canPlayType() | Checks whether the browser can play the specified audio type |
| fastSeek() | Seeks to a specified time in the audio player |
| getStartDate() | Returns a new Date object, representing the current timeline offset |
| load() | Re-loads the audio element |
| play() | Starts playing the audio |
| pause() | Pauses the currently playing audio |
В современной веб-разработке синхронизацией нескольких аудио проще управлять с помощью JavaScript:
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>media-group</title>
</head>
<body>
<h1>Синхронизация аудио с помощью media-group</h1>
<audio id="audio1" src="./audio/original_de_audio_Hoeren-Sprechen_A2_Track_002.mp3" controls></audio>
<audio id="audio2" src="./audio/ru_audio_tra_Hoeren-Sprechen_A2_Track_002.mp3" controls></audio>
<script>
const audio1 = document.getElementById('audio1');
const audio2 = document.getElementById('audio2');
audio1.addEventListener('play', () => {
audio2.play().catch((err) => console.error(err)); // В браузере может сработать autoplay policy
});
audio1.addEventListener('pause', () => {
audio2.pause();
});
</script>
</body>
</html>