在react-native-video中播放youtube视频

时间:2019-08-08 12:56:04

标签: react-native react-native-video

如何在react-native-video上播放youtube视频,

我不想在react-native-youtube或webview中播放视频,

提前谢谢。

Blockquote

5 个答案:

答案 0 :(得分:2)

react-native-video不支持YouTube播放。这是我们一直在研究自己的项目的东西。由于直接公开了HLS和MP4文件,它将支持Vimeo专业视频的播放,但是YouTube不能可靠地提供此功能。有时候以前可以从某些YouTube视频中获取直接视频URL,但现在已经不可靠了,might not even be possible with the latest API.

当前,我们一直在转储到YouTube应用或YouTube网站上,以避免必须实施官方的react-native-youtube存储库,但我们最终将与该存储库集成,以提供更加无缝的用户体验。

我知道您不想使用此解决方案,但是很遗憾,此问题目前不适合使用react-native-video,并且可能永远不会使用。有关更多信息,请参见此SO question

答案 1 :(得分:1)

我检查并使用的另一个选项是WebView。要使用它,请确保将组件放在带有flex的View中。例如:

<View style={{flex: 1}}>
      <WebView
                style={ {  marginTop: (Platform.OS == 'ios') ? 20 : 0,} }
                javaScriptEnabled={true}
                domStorageEnabled={true}
                source={{uri: 'https://www.youtube.com/embed/'+this.state.pictureData.idVideo }}
        />
      </View>

在我的情况下,我所做的就是获取YouTube视频的标识部分,例如:https://www.youtube.com/watch?v= KQ6zr6kCPj8

this.state.pictureData.idVideo仅包含:KQ6zr6kCPj8

要使用它,请安装:

  1. $ npm install --save react-native-webview
  2. 链接react-native-webview

,如果您需要更多信息: https://github.com/react-native-community/react-native-webview

答案 2 :(得分:1)

您的问题的一种解决方案是使用本机youtube。

react-native-youtube

这是我尝试的示例:

import React, { Component } from 'react';
import  { StyleSheet,  View,  Text,  ScrollView,  TouchableOpacity,  PixelRatio,         Platform,  Button,  Dimensions, } from 'react-native';
import YouTube, { YouTubeStandaloneIOS, YouTubeStandaloneAndroid } from 'react-native-youtube';



export default class YouTubeExample extends Component {
state = {
  isReady: false,
  status: null,
  quality: null,
  error: null,
  isPlaying: true,
  isLooping: true,
  duration: 0,
  currentTime: 0,
  fullscreen: false,
  playerWidth: Dimensions.get('window').width,
 };
 constructor(props){
    super(props);
 }

 _youTubeRef = React.createRef();

render(){
  const YOUR_API_KEY = "paste yout api key here";

 return (<View>
      <ScrollView style={styles.container}>
        <Text style={styles.welcome}>{'<YouTube /> component for React Native.'}    </Text>
    <YouTube
      ref={this._youTubeRef}
      // You must have an API Key for the player to load in Android
      apiKey = {YOUR_API_KEY}
      // Un-comment one of videoId / videoIds / playlist.
      // You can also edit these props while Hot-Loading in development mode to see how
      // it affects the loaded native module
      //videoId="ncw4ISEU5ik"
      // videoIds={['uMK0prafzw0', 'qzYgSecGQww', 'XXlZfc1TrD0', 'czcjU1w-c6k']}
      playlistId="PL3c6c2pNE7cLc5a0zpz7xZOW38H7lzzKM"
      play={this.state.isPlaying}
      loop={this.state.isLooping}
      fullscreen={this.state.fullscreen}
      controls={1}
      style={[
        { height: PixelRatio.roundToNearestPixel(this.state.playerWidth / (16 / 9)) },
        styles.player,
      ]}
      onError={e => {
        this.setState({ error: e.error });
      }}
      onReady={e => {
        this.setState({ isReady: true });
      }}
      onChangeState={e => {
        this.setState({ status: e.state });
      }}
      onChangeQuality={e => {
        this.setState({ quality: e.quality });
      }}
      onChangeFullscreen={e => {
        this.setState({ fullscreen: e.isFullscreen });
      }}
      onProgress={e => {
        this.setState({ currentTime: e.currentTime });
      }}
    />

 {/* Playing / Looping */}
    <View style={styles.buttonGroup}>
      <Button
        title={this.state.status == 'playing' ? 'Pause' : 'Play'}
        color={this.state.status == 'playing' ? 'red' : undefined}
        onPress={() => {
          this.setState(state => ({ isPlaying: !state.isPlaying }));
        }}
      />
      <Text> </Text>
      <Button
        title={this.state.isLooping ? 'Looping' : 'Not Looping'}
        color={this.state.isLooping ? 'green' : undefined}
        onPress={() => {
          this.setState(state => ({ isLooping: !state.isLooping }));
        }}
      />
    </View>

    {/* Previous / Next video */}
    <View style={styles.buttonGroup}>
      <Button
        title="Previous Video"
        onPress={() => {
          if (this._youTubeRef.current) {
            this._youTubeRef.current.previousVideo();
          }
        }}
      />
      <Text> </Text>
      <Button
        title="Next Video"
        onPress={() => {
          if (this._youTubeRef.current) {
            this._youTubeRef.current.nextVideo();
          }
        }}
      />
    </View>

    {/* Go To Specific time in played video with seekTo() */}
    <View style={styles.buttonGroup}>
      <Button
        title="15 Seconds"
        onPress={() => {
          if (this._youTubeRef.current) {
            this._youTubeRef.current.seekTo(15);
          }
        }}
      />
      <Text> </Text>
      <Button
        title="2 Minutes"
        onPress={() => {
          if (this._youTubeRef.current) {
            this._youTubeRef.current.seekTo(2 * 60);
          }
        }}
      />
      <Text> </Text>
      <Button
        title="15 Minutes"
        onPress={() => {
          if (this._youTubeRef.current) {
            this._youTubeRef.current.seekTo(15 * 60);
          }
        }}
      />
    </View>

    {/* Play specific video in a videoIds array by index */}
    {this._youTubeRef.current &&
      this._youTubeRef.current.props.videoIds &&
      Array.isArray(this._youTubeRef.current.props.videoIds) && (
        <View style={styles.buttonGroup}>
          {this._youTubeRef.current.props.videoIds.map((videoId, i) => (
            <React.Fragment key={i}>
              <Button
                title={`Video ${i}`}
                onPress={() => {
                  if (this._youTubeRef.current) {
                    this._youTubeRef.current.playVideoAt(i);
                  }
                }}
              />
              <Text> </Text>
            </React.Fragment>
          ))}
        </View>
      )}

    {/* Get current played video's position index when playing videoIds (and playlist in iOS) */}
    <View style={styles.buttonGroup}>
      <Button
        title={'Get Videos Index: ' + this.state.videosIndex}
        onPress={() => {
          if (this._youTubeRef.current) {
            this._youTubeRef.current
              .getVideosIndex()
              .then(index => this.setState({ videosIndex: index }))
              .catch(errorMessage => this.setState({ error: errorMessage }));
          }
        }}
      />
    </View>

    {/* Fullscreen */}
    {!this.state.fullscreen && (
      <View style={styles.buttonGroup}>
        <Button
          title="Set Fullscreen"
          onPress={() => {
            this.setState({ fullscreen: true });
          }}
        />
      </View>
    )}

    {/* Get Duration (iOS) */}
    {Platform.OS === 'ios' && (
      <View style={styles.buttonGroup}>
        <Button
          title="Get Duration (iOS)"
          onPress={() => {
            if (this._youTubeRef.current) {
              this._youTubeRef.current
                .getDuration()
                .then(duration => this.setState({ duration }))
                .catch(errorMessage => this.setState({ error: errorMessage }));
            }
          }}
        />
      </View>
    )}

    {/* Get Progress & Duration (Android) */}
    {Platform.OS === 'android' && (
      <View style={styles.buttonGroup}>
        <Button
          title="Get Progress & Duration (Android)"
          onPress={() => {
            if (this._youTubeRef.current) {
              this._youTubeRef.current
                .getCurrentTime()
                .then(currentTime => this.setState({ currentTime }))
                .catch(errorMessage => this.setState({ error: errorMessage }));

              this._youTubeRef.current
                .getDuration()
                .then(duration => this.setState({ duration }))
                .catch(errorMessage => this.setState({ error: errorMessage }));
            }
          }}
        />
      </View>
    )}

    {/* Standalone Player (iOS) */}
    {Platform.OS === 'ios' && YouTubeStandaloneIOS && (
      <View style={styles.buttonGroup}>
        <Button
          title="Launch Standalone Player"
          onPress={() => {
            YouTubeStandaloneIOS.playVideo('KVZ-P-ZI6W4')
              .then(() => console.log('iOS Standalone Player Finished'))
              .catch(errorMessage => this.setState({ error: errorMessage }));
          }}
        />
      </View>
    )}

    {/* Standalone Player (Android) */}
    {Platform.OS === 'android' && YouTubeStandaloneAndroid && (
      <View style={styles.buttonGroup}>
        <Button
          style={styles.button}
          title="Standalone: One Video"
          onPress={() => {
            YouTubeStandaloneAndroid.playVideo({
              apiKey: 'YOUR_API_KEY',
              videoId: 'KVZ-P-ZI6W4',
              autoplay: true,
              lightboxMode: false,
              startTime: 124.5,
            })
              .then(() => {
                console.log('Android Standalone Player Finished');
              })
              .catch(errorMessage => {
                this.setState({ error: errorMessage });
              });
          }}
        />
        <Text> </Text>
        <Button
          title="Videos"
          onPress={() => {
            YouTubeStandaloneAndroid.playVideos({
              apiKey: 'YOUR_API_KEY',
              videoIds: ['HcXNPI-IPPM', 'XXlZfc1TrD0', 'czcjU1w-c6k', 'uMK0prafzw0'],
              autoplay: false,
              lightboxMode: true,
              startIndex: 1,
              startTime: 99.5,
            })
              .then(() => {
                console.log('Android Standalone Player Finished');
              })
              .catch(errorMessage => {
                this.setState({ error: errorMessage });
              });
          }}
        />
        <Text> </Text>
        <Button
          title="Playlist"
          onPress={() => {
            YouTubeStandaloneAndroid.playPlaylist({
              apiKey: 'YOUR_API_KEY',
              playlistId: 'PLF797E961509B4EB5',
              autoplay: false,
              lightboxMode: false,
              startIndex: 2,
              startTime: 100.5,
            })
              .then(() => {
                console.log('Android Standalone Player Finished');
              })
              .catch(errorMessage => {
                this.setState({ error: errorMessage });
              });
          }}
        />
      </View>
    )}

    {/* Reload iFrame for updated props (Only needed for iOS) */}
    {Platform.OS === 'ios' && (
      <View style={styles.buttonGroup}>
        <Button
          title="Reload iFrame (iOS)"
          onPress={() => {
            if (this._youTubeRef.current) {
              this._youTubeRef.current.reloadIframe();
            }
          }}
        />
      </View>
    )}

    <Text style={styles.instructions}>
      {this.state.isReady ? 'Player is ready' : 'Player setting up...'}
    </Text>
    <Text style={styles.instructions}>Status: {this.state.status}</Text>
    <Text style={styles.instructions}>Quality: {this.state.quality}</Text>

    {/* Show Progress */}
    <Text style={styles.instructions}>
      Progress: {Math.trunc(this.state.currentTime)}s ({Math.trunc(this.state.duration / 60)}:
      {Math.trunc(this.state.duration % 60)}s)
      {Platform.OS !== 'ios' && <Text> (Click Update Progress & Duration)</Text>}
    </Text>

    <Text style={styles.instructions}>
      {this.state.error ? 'Error: ' + this.state.error : ''}
    </Text>

      </ScrollView>
    </View>
   );
 }
}

const styles = StyleSheet.create({
  container: {
   backgroundColor: 'grey',
 },
welcome: {
  fontSize: 20,
  textAlign: 'center',
  margin: 10,
},
buttonGroup: {
flexDirection: 'row',
alignSelf: 'center',
paddingBottom: 5,
},
instructions: {
  textAlign: 'center',
  color: '#333333',
  marginBottom: 5,
 },
player: {
  alignSelf: 'stretch',
  marginVertical: 10,
 },
});

有关API密钥,请点击以下链接:

API Key

您的地址中包含播放列表的ID:

enter image description here

像这样安装组件:

  • npm install react-native-youtube -S

我在使用'@Nullable'时遇到错误,如果您遇到相同的问题,请转到

  • node_modules \ react-native-youtube \ android \ build.gradle

并在“依赖项”部分中,添加以下行:

  • 实现'androidx.annotation:annotation:1.1.0'

也许您需要清理gradle:

  • cd android
  • gradlew clean(或。\ gradlew clean)

这是我实际的android模拟器的快照:

enter image description here

答案 3 :(得分:0)

嗯,我还没有尝试过,但是在我的项目中我将需要它。在我阅读时,有一个名为: react-native-youtube

的软件包

以下是有关该软件包的信息:https://www.npmjs.com/package/react-native-youtube

如果你等明天,我会检查,我告诉你,如果你愿意,我走了,如果你能知道事情的进展... ^^

答案 4 :(得分:0)

您无法使用react-native-video模块播放Youtube视频。目前不支持此功能,从不支持。而且似乎也没有出现在他们的roadmap中。因此,您应该讨论其他选项,我建议您使用react-native-webview的最新版本。我自己进行了测试,效果很好。特别是我喜欢他们为Android添加了全屏模式的东西。