Перейти к содержимому

javascript audio play

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

PropertyDescription
audioTracks — НЕ поддерживается.Returns an AudioTrackList object representing available audio tracks
Возвращает объект AudioTrackList, представляющий доступные аудиодорожки.
autoplaySets or returns whether the audio should start playing as soon as it is ready
Устанавливает или возвращает, должно ли аудио начинать воспроизводиться сразу после готовности
bufferedReturns a TimeRanges object representing the buffered parts of an audioВозвращает объект TimeRanges, представляющий буферизованные части аудио
controllerReturns the MediaController object representing the current media controller of an audioВозвращает объект MediaController, представляющий текущий медиа-контроллер аудио.
controlsSets or returns whether an audio should have controls displayed (play/pause etc)
Устанавливает или возвращает, должны ли отображаться элементы управления аудио (воспроизведение/пауза и т. д.)
crossOriginSets or returns the CORS settings of an audioУстанавливает или возвращает настройки CORS аудио
currentSrcReturns the URL of the current audioВозвращает URL текущего аудио
currentTimeSets or returns the current playback position in an audio (in seconds)

Устанавливает или возвращает текущую позицию воспроизведения в аудио (в секундах)
defaultMutedSets or returns whether the audio should be muted by default
Устанавливает или возвращает значение, следует ли отключать звук по умолчанию.
defaultPlaybackRateSets or returns whether the default playback speed of the audio
Устанавливает или возвращает значение скорости воспроизведения звука по умолчанию.
durationReturns the length of an audio(in seconds)Возвращает длительность аудио (в секундах)
endedReturns whether the playback of the audio has endedReturns whether the playback of the audio has ended
errorReturns a MediaError object representing the error state of the audioВозвращает объект MediaError, представляющий состояние ошибки аудио.
loopSets or returns whether the audio should start playing over again, every time it is finished
Устанавливает или возвращает, должно ли воспроизведение звука начинаться заново каждый раз после его завершения
mediaGroupSets or returns the name of the media group the audio(s) is a part of





Устанавливает или возвращает имя медиагруппы, частью которой является аудио (браузеры так и не внедрили эту функциональность.) Внизу пример как управлять двумя плеерами одновременно посредством JS.
mutedSets or returns whether the sound should be turned offЗвук включен или выключен.
networkStateReturns the current network state of an audio
pausedReturns whether an audio is paused
playbackRateSets or returns the speed of the audio playback
playedReturns a TimeRanges object representing the played parts of the audio
preloadSets or returns the value of the preload attribute of an audio
readyStateReturns the current ready state of an audio
seekableReturns a TimeRanges object representing the seekable parts of an audio
seekingReturns whether the user is currently seeking in the audio
srcSets or returns the value of the src attribute of an audio
textTracksReturns a TextTrackList object representing the available text tracks
volumeSets or returns the audio volume of an audio


Audio Object Methods

MethodDescription
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>