0

I am working on React native App and am facing some issue in react-native-video doesn't have the feature to play a youtube video for that you have to use external libraries react-native-youtube so,now also facing some issue with them...

My App Requirement - is playing youtube video and when we close the app still audio is run in background !

My App.js file

import React, {useEffect, useState} from 'react';
import {View, StyleSheet} from 'react-native';
import Video from 'react-native-video';

const VIDEO_URL = 'https://www.youtube.com/watch?v=z1qG80Jkzi8';

const App = () => {
  const [videoUrl, setVideoUrl] = useState('');

  useEffect(() => {
    const getYouTubeVideoId = url => {
      const videoId = url.split('v=')[1];
      const ampersandPosition = videoId.indexOf('&');
      if (ampersandPosition !== -1) {
        return videoId.substring(0, ampersandPosition);
      }
      return videoId;
    };

    const extractVideoUrl = async () => {
      try {
        const videoId = getYouTubeVideoId(VIDEO_URL);
        const apiUrl = `https://www.youtube.com/get_video_info?video_id=${videoId}`;

        const response = await fetch(apiUrl);
        const data = await response.text();

        const decodedData = decodeURIComponent(data);

        const videoInfo = decodedData.split('&').reduce((acc, item) => {
          const parts = item.split('=');
          acc[parts[0]] = parts[1];
          return acc;
        }, {});

        const videoStreams = JSON.parse(videoInfo.player_response).streamingData
          .formats;
        const highestQualityVideo = videoStreams.reduce((acc, stream) => {
          if (stream.width > acc.width) {
            return stream;
          }
          return acc;
        });

        setVideoUrl(highestQualityVideo.url);
      } catch (error) {
        console.error('Error fetching video URL:', error);
      }
    };

    extractVideoUrl();

    return () => {
      // Cleanup logic if needed
    };
  }, []);

  return (
    <View style={styles.container}>
      {videoUrl ? (
        <Video
          source={{uri: videoUrl}}
          style={styles.videoPlayer}
          resizeMode="cover"
          repeat={true}
          muted={true}
        />
      ) : null}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  videoPlayer: {
    flex: 1,
  },
});

export default App;

Error in this code -

 ERROR  Error fetching video URL: [SyntaxError: JSON Parse error: Unexpected token: u]
Pankaj
  • 73
  • 1
  • 8

0 Answers0