How to set the currentTime in HTML5 audio object when audio file is online?

Igid

I have a JavaScript audio player with skip forward/back 10 second buttons. I do this by setting the currentTime of my audio element:

function Player(skipTime)
{
    this.skipTime = skipTime;
    this.waitLoad = false;

    // initialise main narration audio
    this.narration = new Audio(getFileName(dynamicNarration));
    this.narration.preload = "auto";
    this.narration.addEventListener('canplaythrough', () => { this.loaded();       });
    this.narration.addEventListener('timeupdate',     () => { this.seek();         });
    this.narration.addEventListener('ended',          () => { this.ended();        });
    this.narration.addEventListener('waiting',        () => { this.audioWaiting(); });
    this.narration.addEventListener('playing',        () => { this.loaded();       });
}

Player.prototype = {
    rew: function rew()
    {
        if (!this.waitLoad) {
            this.skip(-this.skipTime);
        }
    },

    ffw: function ffw()
    {
        if (!this.waitLoad) {
            this.skip(this.skipTime);
        }
    },

    skip: function skip(amount)
    {
        const curTime = this.narration.currentTime;
        const newTime = curTime + amount;
        console.log(`Changing currentTime (${curTime}) to ${newTime}`);
        this.narration.currentTime = newTime;
        console.log(`Result: currentTime = ${this.narration.currentTime}`);
    },

    loaded: function loaded()
    {
        if (this.waitLoad) {
            this.waitLoad = false;
            playButton.removeClass('loading');
        }
    },

    audioWaiting: function audioWaiting()
    {
        if (!this.waitLoad) {
            this.waitLoad = true;
            playButton.addClass('loading');
        }
    },
}

(I'm including here some of the event listeners I'm attaching because previously I'd debugged a similar problem as being down to conflicts in event listeners. Having thoroughly debugged event listeners this time though, I don't think that's the root of the problem.)

Though this all works fine on my local copy, when I test an online version I get the following results:

  • Chrome: resets play position to 0. Final console line reads Result: currentTime = 0.
  • Safari: doesn't change play position at all. Final console.log line gives a value for currentTime equal to newTime (even though the play position actually doesn't change).
  • Firefox: skipping forward works; skipping backwards interrupts the audio for a few seconds, then it starts playing again from a couple of seconds before where the playhead had been. In both cases, final console.log line gives a value for currentTime equal to newTime

The issue must have something to do with the way audio is loaded. I have tried adding another console log line to show the start and end values for buffered.

In Chrome it goes up to 2 seconds after current play position. In Safari it goes up to ~170 seconds, and in Firefox it seems to buffer the full audio length.

However, in each case the start of the buffered object is 0.

Does anyone have any idea what might be going wrong?

Igid

I found a solution to my problem, if not exactly an explanation.

My hosting provider uses a CDN, for which it must replace resource's URLs with those of a different domain. The URLs of my audio resources are dynamically constructed by JS, because there's a random element to them; as such, the deployment process that replaces URLs wasn't catching those for my audio files. To get around this, I manually excluded the audio files from the CDN, meaning I could refer to them using relative file paths.

This was how things stood when I was having this issue.

Then, due to a separate issue, I took a different approach: I got the audio files back on the CDN and wrote a function to extract the domain name I needed to use to retrieve the files. When I did that, suddenly I found that all my problems to do with setting currentTime had disappeared. Somehow, not having the files on the CDN was severely interfering with the browser's ability to load them in an orderly manner.

If anyone can volunteer an explanation for why this might have been, I'd be very curious to hear it...

Edit

I've been working on another project which involves streaming audio, this time also with PWA support, so I had to implement a caching mechanism in my service worker for audio files. Through this guide I learned all about the pitfalls of range requests, and understand now that failing to serve correct responses to requests with range headers will break seeking on some browsers.

It seems that in the above case, when I excluded my files from the CDN they were served from somewhere that didn't support range headers. When I moved them back on the CDN this was fixed, as it must have been built with explicit support for streaming media.

Here is a good explanation of correct responses to range requests. But for anyone having this issue while using a third party hosting service, it suffices to know that probably they do not support range headers for streaming media. If you want to verify this is the case, you can query the audio object's duration. At least in Safari's case, the duration is set to infinity when it can't successfully make a range request, and at that point seeking will be disabled.

Эта статья взята из Интернета, укажите источник при перепечатке.

Если есть какие-либо нарушения, пожалуйста, свяжитесь с[email protected] Удалить.

Отредактировано в
0

я говорю два предложения

0обзор
Войти в системуУчаствуйте в комментариях

Статьи по теме

HTML5 audio - currentTime attribute inaccurate?

html5 audio: изменение currentTime запускает несколько событий canplay

Получение HTML5 audio "currentTime" и "duration" в Python

Преобразование <audio> currentTime в отображение точного времени

Получатели Vuex в реальном времени обновляют состояние audio.currentTime

javascript <audio>: не могу обновить currentTime

установка audio.currentTIme; с буфером песен, отправленным с экспресс-сервера

Как заставить тег HTML5 Audio перезагружать (изменяющийся) файл

Почему Html5 Audio загружает все песни с сервера при загрузке файла

HTML5 Audio - Получение массива частот, заполненного нулями

Тег html5 <audio> загружает звук с сервера перед активацией?

Как передать музыку из потокового сервиса в элемент HTML5 <audio>?

Контейнер потоковой передачи для тега HTML5 <audio>

Как передать музыку из потокового сервиса в элемент HTML5 <audio>?

Автовоспроизведение следующего html5 <audio> при завершении предыдущего элемента

html5 audio: нажмите, чтобы воспроизвести, нажмите еще раз, чтобы приостановить воспроизведение нескольких треков.

Произвести случайное изменение начальной точки воспроизведения в html5 Audio при переключении

Я могу получить audio.currentTime, но не могу установить его (в Google Chrome)

html Audio currentTime и FileResult в asp.net MVC

Click text words to read adjacent html5 audio file

HTML Audio Object сообщает неправильную продолжительность файла

HTML5 audio говорит о "прямой трансляции" в iOS, когда это статический файл.

html5 audio player: воспроизведение с / на треки

HTML5 Audio не может воспроизводиться через Javascript, если не активирован вручную один раз

HTML5 Audio Looping

HTML5 Audio styling

Создание параметра типа для HTML5 <audio> программно с помощью Javascript

HTML5 Audio Tag - начало и конец в позиции

html5 audio addeventhandler

TOP список

  1. 1

    Распределение Рэлея Curve_fit на Python

  2. 2

    How to click an array of links in puppeteer?

  3. 3

    В типе Observable <unknown> отсутствуют следующие свойства из типа Promise <any>.

  4. 4

    Как добавить Swagger в веб-API с поддержкой OData, работающий на ASP.NET Core 3.1

  5. 5

    Нарисуйте диаграмму с помощью highchart.js

  6. 6

    无法通过Vue在传单中加载pixiOverlay

  7. 7

    Отчеты Fabric Debug Craslytic: регистрация, отсутствует идентификатор сборки, применить плагин: io.fabric

  8. 8

    Статус HTTP 403 - ожидаемый токен CSRF не найден

  9. 9

    TypeError: store.getState não é uma função. (Em 'store.getState ()', 'store.getState' é indefinido, como posso resolver esse problema?

  10. 10

    ContentDialog.showAsync в универсальном оконном приложении Win 10

  11. 11

    В UICollectionView порядок меняется автоматически

  12. 12

    Merging legends in plotly subplot

  13. 13

    Elasticsearch - Нечеткий поиск не дает предложения

  14. 14

    Bogue étrange datetime.utcnow()

  15. 15

    Объединение таблиц в листе Google - полное соединение

  16. 16

    Single legend for Plotly subplot for line plots created from two data frames in R

  17. 17

    как я могу удалить vue cli 2?

  18. 18

    ViewPager2 мигает / перезагружается при смахивании

  19. 19

    Компилятор не знает о предоставленных методах Trait

  20. 20

    JDBI - В чем разница между @define и @bind в JDBI?

  21. 21

    проблемы с AVG и LIMIT SQL

популярныйтег

файл