React - refs - 音频播放 - iOS 上未处理的拒绝 (NotSupportedError)

React - refs - audio playback - Unhandled Rejection (NotSupportedError) on iOS

我构建了一个 React 应用,plays/pauses 当前选择的音频在桌面网络浏览器上运行良好:

playPreview() {
    if (!this.state.isPlaying) {
      this.setState({ isPlaying: true });
      this.refs.audioRef.play();
    } else {
      this.setState({ isPlaying: false });
      this.refs.audioRef.pause();
    }
  }

在 iOS 移动浏览器(safari 和 chrome 移动浏览器)上,我收到未处理的拒绝(NotSupprted 错误):不支持该操作。

我知道在 iOS 上必须通过用户手势播放音频的问题,但我使用 onClick 触发了我的方法:

{!props.isPlaying 
  ? (<MdPlayCircleOutline className="play-btn" onClick={() => 
    props.playPreview()} />) 
  : (<MdPauseCircleOutline className="play-btn" onClick={() => 
    props.playPreview()} />)
}

我在父应用程序组件中有一个隐藏元素:

<audio ref="audioRef" src={this.state.currentSongUrl} style={{ display: 'none' }} />

所以我假设它不起作用,因为 onClick 不是直接的音频元素?如果是这样的话,我确定如何将这两个要求结合起来。

1 - 动态改变音频源 2 - 交替播放和暂停

在此先感谢您的任何见解和帮助!

-托德

发生这种情况的原因可能是您对 ref 使用了已弃用的语法。你应该尝试这样的事情:

<audio ref={(input) => {this.audioRef = input}} src={this.state.currentSongUrl} style={{ display: 'none' }} />

playPreview() {
  if (!this.state.isPlaying) {
    this.setState({ isPlaying: true });
    this.audioRef.play();
  } else {
    this.setState({ isPlaying: false });
    this.audioRef.pause();
  }
}

如需参考,请访问:Refs and the DOM

我用

import React from 'react'
import ReactPlayer from "react-audio-player";

let ref = null;
const stats = {play:false};

const Player = props => {
return (
    <div key={`props.id`}>
        <ReactPlayer
            src={`props.src`}
            ref={(el)=> {ref = el} }
            controls
        />
        <div onClick={()=>start()}>
            x
        </div>
    </div>
)
}
function start() {
    stats.play = !stats.play;
    console.log(stats, ref)

    if(stats.play){
        ref.audioEl.current.play()
    }else{
        ref.audioEl.current.pause()
    }
}

ReactDOM.render( <Player src="https://www.w3schools.com/html/horse.mp3" id="p1" /> , document.getElementById('root') );