如何在React Native中播放vimeo视频?

ycggw6v2  于 2023-03-19  发布在  React
关注(0)|答案(6)|浏览(148)

我有一个要求在我的React原生应用程序中播放Vimeo视频。我正在使用webview播放视频,视频播放,但我看不到屏幕上的任何东西,音频来了,但屏幕是空白的。下面是我的代码。有什么我做错了或任何其他方式来播放Vimeo?任何帮助将不胜感激。

<AutoHeightWebView
    startInLoadingState
    style={{ width: "100%", height: '100%', borderColor: 'white', borderWidth: 2 }}
    source={{
        uri: 'https://player.vimeo.com/video/299264098?autoplay=1' //'this.state.videoUrl'
    }}
    onError={() => console.log('on error')}
    onLoad={() => console.log('on load')}
    onLoadStart={() => console.log('on load start')}
    onLoadEnd={() => console.log('on load end')}

    bounces={false}
/>
edqdpe6u

edqdpe6u1#

我发现了一种方法来运行一个vimeo视频在React原生。简单地说,你必须请求的网址,以获得它的详细配置通过vimeo的id。里面的配置,你会发现videoUrl,这可以很容易地运行在React原生视频控件。

示例如下

const VIMEO_ID = '179859217';
fetch(`https://player.vimeo.com/video/${VIMEO_ID}/config`)
      .then(res => res.json())
      .then(res => this.setState({
        thumbnailUrl: res.video.thumbs['640'],
        videoUrl: res.request.files.hls.cdns[res.request.files.hls.default_cdn].url,
        video: res.video,
      }));

渲染中

<VideoPlayer
        ref={ref => {
          this.player = ref;
        }}
        source={{uri: this.state.videoUrl}}
        navigator={this.props.navigator}
        fullscreen={true}
        resizeMode={'cover'}
      />
uxhixvfz

uxhixvfz2#

我找到了一个在webview上嵌入iframe的解决方案。

import React from 'react';
import { string, func } from 'prop-types';
import WebView from 'react-native-autoheight-webview';

const VimeoPlayer = ({ videoId, onError }) => {
  return (
    <WebView
      style={style}
      onError={onError}
      allowsFullscreenVideo
      scrollEnabled={false}
      automaticallyAdjustContentInsets
      source={{
        html: `
          <html>
            <body>
              <iframe src="https://player.vimeo.com/video/${videoId}" width="100%" height="200px" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
              <script src="https://player.vimeo.com/api/player.js"></script>
            </body>
          </html>
        `,
      }}
    />
  );
};

const style = {
  height: 200,
  maxWidth: '100%',
};

VimeoPlayer.propTypes = {
  videoId: string,
  onError: func,
};

export default VimeoPlayer;
fnx2tebb

fnx2tebb3#

简短回答:使用progressive文件,而不是hls。这些文件似乎包含指向mp4文件的链接,expo-av在Android和iOS上都支持mp4文件,无论您的项目是一个裸React Native项目,还是由Expo管理。
the solution posted by Zuhair Naqi类似,但使用res.request.files.progressive中对象的url,而不是res.request.files.hls.cdns[res.request.files.hls.default_cdn].url
下例中的函数将返回一个对象列表,其中包含指向不同分辨率视频的链接。

function getVimeoLinks(url: string) {
  return fetch(`https://vimeo.com/api/oembed.json?url=${url}`, {
    headers: {
      'content-type': 'application/json',
      accept: 'application/json'
    }
  })
    .then(r => r.json())
    .then(({ video_id }) =>
      fetch(`https://player.vimeo.com/video/${video_id}/config`)
    )
    .then(r => r.json())
    .then(
      r =>
        r.request.files.progressive as {
          profile: number;
          width: number;
          mime: string;
          fps: number;
          url: string;
          cdn: string;
          quality: string;
          id: number;
          origin: string;
          height: number;
        }[]
    );
}

然后,对于您的组件,执行如下操作:

import { Video } from 'expo-av';

// Hook for getting some Vimeo video url (mp4)
function useVimeoUrl(url: string) {
  const [state, setState] = useState<undefined | string>();
  useEffect(() => {
    getVimeoConfig(url).then(r => setState(r[0].url));
  }, [url]);
  return state;
}

// Render video
function MyComponent({ url }: { url: string }) {
  // State containing video url
  const vimeoUrl = useVimeoUrl(url);

  // Render
  return vimeoUrl ? <Video source={{ uri: vimeoUrl }} /> : <></>;
}
oogrdqng

oogrdqng4#

尝试使用react-native-video包在React Native项目中播放Vimeo视频。
使用npm安装

npm install --save react-native-video

或者使用yarn

yarn add react-native-video

以下链接中可能出现的问题值得注意。
https://stackoverflow.com/a/52976151/5519329
https://stackoverflow.com/a/39982973/5519329

代码:

import Video from 'react-native-video';

<Video source={{uri: "your url"}}   // Can be a URL or a local file.
       ref={(ref) => {
         this.player = ref
       }}                                      // Store reference
       onBuffer={this.onBuffer}                // Callback when remote video is buffering
       onEnd={this.onEnd}                      // Callback when playback finishes
       onError={this.videoError}               // Callback when video cannot be loaded
       style={styles.backgroundVideo} />

// Later on in your styles..
var styles = StyleSheet.create({
  backgroundVideo: {
    position: 'absolute',
    top: 0,
    left: 0,
    bottom: 0,
    right: 0,
  },
});
n1bvdmb6

n1bvdmb65#

我在尝试在应用程序中显示嵌入式Vimeo视频时遇到了同样的问题。使用html内容的解决方案(如Juliano所示)非常适合我

qlzsbp2j

qlzsbp2j6#

你可以使用 Vimeo 提供的oEmbed api,它会为相关视频生成一个可嵌入的<iframe>元素,你可以在钩子中使用一个函数,如下所示:

React.useEffect(() => {
setLoading(true);

(async function init() {
  try {
    const urlParts = url.split("/");
    const channelID = urlParts[urlParts.length - 2];
    const videoID = urlParts[urlParts.length - 1];
    const videoURL = `https://vimeo.com/${channelID}/${videoID}`;

    const requestURL = `https://vimeo.com/api/oembed.json?url=${videoURL}&height=${400}`;

    const { data } = await axios(requestURL);
    setHtml(data.html);
  } catch (err) {
    console.error(err);
  } finally {
    setLoading(false);
  }
})();
}, [url]);

videoURL参数将取决于视频发布的频道类型。

相关问题