【问题标题】:React - refs - audio playback - Unhandled Rejection (NotSupportedError) on iOSReact - refs - 音频播放 - iOS 上的未处理拒绝(NotSupportedError)
【发布时间】:2018-02-12 13:51:19
【问题描述】:

我构建了一个反应应用程序,可以在桌面网络浏览器上播放/暂停当前选择的音频:

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 mobile)上,我收到未处理的拒绝(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 - 交替播放和暂停

提前感谢任何见解和帮助!

-托德

【问题讨论】:

    标签: reactjs media


    【解决方案1】:

    这可能是因为您使用了不推荐使用的 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

    【讨论】:

    • 非常感谢您的帮助!
    【解决方案2】:

    我用

    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') );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-30
      • 1970-01-01
      • 1970-01-01
      • 2020-05-21
      相关资源
      最近更新 更多