I am currently working on a reactjs project which uses a flask server backend and currently I am trying to implement a streaming component.
Since browsers aren’t as easy as VLC when connecting to external .m3u8 streams due to CORS Policies, I was playing around with the idea of calling the stream from flask and passing it to react through and endpoint.
I am currently getting the following errors in console and no stream.
ReactJs Component:
import React, { useEffect, useRef } from 'react';
import Hls from 'hls.js';
const LiveTVPlayer = (props) => {
const videoRef = useRef(null);
useEffect(() => {
const video = videoRef.current;
const m3u8Url = 'http://{My Flask Server Url}/api/Live';
if (Hls.isSupported()) {
const hls = new Hls();
hls.loadSource(m3u8Url);
hls.attachMedia(video);
hls.on(Hls.Events.MANIFEST_PARSED, () => {
video.play();
});
hls.on(Hls.Events.ERROR, (event, data) => {
console.error('HLS error:', data);
});
return () => {
hls.destroy();
};
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = m3u8Url;
video.addEventListener('loadedmetadata', () => {
video.play();
});
}
}, []);
return <video ref={videoRef} controls style={{ width: '100%', height: 'auto' }} />;
};
export default LiveTVPlayer;
Flask Endpoint:
@app.route('/Live', methods=['GET'])
def Get_LiveStream():
m3u8_url = 'https://demo.unified-streaming.com/k8s/features/stable/video/tears-of-steel/tears-of-steel.ism/.m3u8'
# Make the GET request to get the HLS stream
response = requests.get(m3u8_url, stream=True)
# Check the response status
if response.status_code == 200:
# Set the response mimetype
headers = {'Content-Type': 'application/vnd.apple.mpegurl'}
# Define a generator function to read and yield chunks of data
def generate():
for chunk in response.iter_content(chunk_size=1024): # Adjust the chunk size as needed
if chunk:
yield chunk
# Stream the HLS content in chunks to the client
return Response(stream_with_context(generate()), headers=headers)
else:
return Response("Failed to fetch live TV stream", status=response.status_code)
Anyone know what could be causing this issue or maybe a better way to implement this ?
(Please keep in mind this is the first time I am working with m3u8)
I broke down and tried to console chatGPT but still to no avail.