Воспроизведение аудио safari с помощью AudioContext работает только после изменения устройства в настройках системы. - PullRequest
0 голосов
/ 09 июля 2019

Я пытаюсь создать компонент React TestSound, который воспроизводит звук с заданным коэффициентом усиления.Однако я не могу заставить его работать в Safari (версия 12.1.1) на MacOS. Я не получаю сообщение об ошибке.

В Chrome и Firefox код работает должным образом.

В Safari звук будет воспроизводиться только тогда, когда динамик в системных настройках был изменен после инициализации.Например, если страница инициализирована с динамиками Mac, установленными в качестве устройства по умолчанию в настройках, мне сначала нужно заменить устройство по умолчанию на мою гарнитуру.Звук будет воспроизводиться через гарнитуру.

Это компонент;Я попытался удалить весь ненужный код:

import React, { Component, Fragment } from 'react';

export default class TestSound extends Component {

    //initalize
    constructor(props) {
        super(props);

        this.state = {
            gain: 1,
        }

        //init audio context
        this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
        this.gainNode = this.audioContext.createGain();
        this.destination = this.audioContext.createMediaStreamDestination();
        this.gainNode.connect(this.destination);
        this.audio = null;

        //fetch sound buffer
        const request = new XMLHttpRequest();
        request.open('GET', '/audio/sound.mp3', true);
        request.responseType = 'arraybuffer';

        request.onload = () => {
            this.audioContext.decodeAudioData(request.response, buffer => {
                this.buffer = buffer;
                this.audio.srcObject = this.destination.stream;
            });
        }
        request.send();
    }

    //play the sound
    onAudioClick = e => {
        this.source = this.audioContext.createBufferSource();
        this.source.buffer = this.buffer;
        this.source.connect(this.gainNode);
        this.gainNode.gain.value = this.state.gain;
        this.source.start(0);
    }

    //set the ref and destination stream for the audio element
    audioMounted = ref => {
        if (!this.audio) {
            this.audio = ref;
            this.audio.srcObject = this.destination.stream;
        }
    }


    //render slider, play button and audio tag
    render() {
        return (
            <Fragment>
                <input type="range" max="1" min="0" step="0.05" onChange={(e) => {this.setState({gain: e.target.value})}}/>
                <button type="button" onClick={this.onAudioClick} >
                    <audio ref={ref => this.audioMounted(ref)} autoPlay/>
                    Play!
                </button>
            </Fragment>
        );
    }
}

Это проблема с версией или ошибка кода?Кто-нибудь еще сталкивался с этой проблемой?

...