javascript 如何在React Native中播放私人YouTube

b4lqfgs4  于 2023-06-20  发布在  Java
关注(0)|答案(1)|浏览(115)

我有一个React原生应用程序,我应该在上面播放私人YouTube视频。我很难整合这个功能。我找到了一个解决方案,但它也不起作用。在这里,我从谷歌开发者控制台获得了一个youyube API密钥,然后使用它。下面是我的代码:

import React, { useState, useEffect } from 'react';
import { WebView } from 'react-native-webview';
import { View } from 'react-native';
const YoutubeVideos = () => {
    const [videoUrl, setVideoUrl] = useState('');
    useEffect(() => {
        const fetchVideoUrl = async () => {
            try {
                const apiKey = 'API_KEY';
                const videoId = 'XXXXXXX';

                const response = await fetch(
                    `https://www.googleapis.com/youtube/v3/videos?part=player&id=${videoId}&key=${apiKey}`
                );
                const data = await response.json();
                const fetchedVideoId = data.items[0].id;
                const videoUrl = `https://www.youtube.com/embed/${fetchedVideoId}?autoplay=1&playsinline=1`;
                setVideoUrl(videoUrl);
                console.log("videoUrl: ", videoUrl);
            } catch (error) {
                console.log(error);
            }
        };

        fetchVideoUrl();
    }, []);
    return (
        <View style={{ flex: 1 }}>
            <WebView
                allowsFullscreenVideo={true}
                useWebKit={true}
                source={{ uri: videoUrl }}
            />
        </View>
    )
}
export default YoutubeVideos

但这也是行不通的。我做错什么了吗?是否有其他方法来处理这个问题?或者甚至可以在React Native上播放私人YouTube视频?

t98cgbkg

t98cgbkg1#

请尝试以下步骤:

1. npm install react-native-webview react-native-youtube react-native-community/netinfo
2. npx react-native link react-native-youtube

Replace VIEW

<View style={styles.container}>
        {videoUrl ? (
          <WebView
            style={styles.webView}
            allowsFullscreenVideo
            allowsInlineMediaPlayback
            source={{ uri: videoUrl }}
          />
        ) : (
          <YouTube
            videoId="XXXXXXX" // Replace with your video ID
            play
            fullscreen
            loop
            style={styles.youtube}
            
          />
        )}
      </View>

相关问题