我正在尝试一个javascript播放按钮,启动嵌入式视频。
一切都在本地运行127.0.0.1:5000,如果我点击红色播放按钮,视频就会播放。但如果我点击html页面上的播放按钮,嵌入的视频会产生以下错误。
我已经在这个问题上坚持了几天,所以我决定来这里发布我所有的代码,我本来会使用片段,但我认为你可能需要复习所有的代码。
此外,一旦我点击html播放按钮,它只显示一个带有红色播放按钮的黑色视频窗口,然后点击红色按钮将在屏幕截图上产生错误。
应用程序.py
import os
from flask import Flask, render_template, request, url_for
from googleapiclient.discovery import build
from youtube_transcript_api import YouTubeTranscriptApi
from gtts import gTTS
app = Flask(__name__)
# Enter your API key here
API_KEY = 'redacted'
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
video_url = request.form['video_url']
video_id = get_video_id(video_url)
# Retrieve the video transcript
try:
transcript = YouTubeTranscriptApi.get_transcript(video_id)
subtitles = [{'text': entry['text'], 'start': entry['start']} for entry in transcript]
# Generate audio files for each subtitle if they don't exist
for subtitle in subtitles:
audio_path = f'audio/{subtitle["start"]}.mp3'
audio_full_path = os.path.join(app.static_folder, audio_path)
if not os.path.isfile(audio_full_path):
tts = gTTS(text=subtitle['text'], lang='en', tld='com') # Specify tld='com' for female voice
tts.save(audio_full_path)
subtitle['audio_path'] = audio_path
except:
subtitles = []
# Retrieve the video details using the YouTube Data API
try:
youtube = build('youtube', 'v3', developerKey=API_KEY)
video_info = youtube.videos().list(part='snippet', id=video_id).execute()
video_title = video_info['items'][0]['snippet']['title']
video_embed_url = f"https://www.youtube.com/embed/{video_id}"
return render_template('result.html', video_title=video_title, video_embed_url=video_embed_url, subtitles=subtitles)
except:
return render_template('result.html', error_message='Failed to retrieve video details')
return render_template('index.html')
def get_video_id(video_url):
# Parse the video ID from the URL
video_id = video_url.split('v=')[1]
return video_id
if __name__ == '__main__':
app.run(debug=True)
结果.html
<!DOCTYPE html>
<html>
<head>
<title>Video Result</title>
</head>
<body>
<h1>{{ video_title }}</h1>
{% if error_message %}
<p>{{ error_message }}</p>
{% else %}
<div>
<iframe id="video-player" width="560" height="315" src="{{ video_embed_url }}" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>
<div>
<button id="play-button" onclick="playVideo()">Play Video</button>
</div>
<div>
{% for subtitle in subtitles %}
<p>{{ subtitle['text'] }}</p>
<audio controls>
<source src="{{ url_for('static', filename=subtitle['audio_path']) }}" type="audio/mpeg">
</audio>
{% endfor %}
</div>
{% endif %}
<script>
console.log("Video Embed URL:", "{{ video_embed_url }}");
function playVideo() {
var videoPlayer = document.getElementById('video-player');
videoPlayer.src += "&autoplay=1";
document.getElementById('play-button').style.display = 'none';
}
</script>
</body>
</html>
索引html
<!DOCTYPE html>
<html>
<head>
<title>dub.dat(youtube)</title>
<script>
function displayProgress() {
var progressBar = document.getElementById("progress-bar");
progressBar.style.display = "block";
}
</script>
</head>
<body>
<h1>YouTube Subtitle Scraper</h1>
<form action="/" method="POST" onsubmit="displayProgress()">
<label for="video_url">YouTube Video URL:</label>
<input type="text" name="video_url" id="video_url" required>
<input type="submit" value="Submit">
</form>
<progress id="progress-bar" style="display: none;"></progress>
</body>
</html>
视频.js
function formatTime(time) {
var hours = Math.floor(time / 3600);
var minutes = Math.floor((time % 3600) / 60);
var seconds = Math.floor(time % 60);
var formattedTime = ("0" + hours).slice(-2) + ":" + ("0" + minutes).slice(-2) + ":" + ("0" + seconds).slice(-2);
return formattedTime;
}
function playSubtitle(subtitleData) {
var currentTime = Math.floor(videoPlayer.currentTime);
for (var i = 0; i < subtitleData.length; i++) {
var subtitle = subtitleData[i];
var startTime = Math.floor(subtitle.start);
var endTime = Math.floor(subtitle.start + subtitle.duration);
if (currentTime >= startTime && currentTime <= endTime) {
// Display the subtitle
var subtitleElement = document.getElementById("translatedSubtitle");
subtitleElement.textContent = subtitle.translatedText;
// Check if translation is needed
if (subtitle.text !== subtitle.translatedText) {
// Run GTTS for the translated subtitle
var tts = new SpeechSynthesisUtterance(subtitle.translatedText);
speechSynthesis.speak(tts);
}
}
}
}
function syncSubtitle(audioPlayer) {
var startTime = parseFloat(audioPlayer.id);
videoPlayer.currentTime = startTime;
}
var videoPlayer = document.getElementById('videoPlayer');
var subtitles = {{ subtitles|tojson }};
var audioPlayers = document.getElementsByTagName('audio');
videoPlayer.addEventListener('timeupdate', function() {
playSubtitle(subtitles);
});
for (var i = 0; i < audioPlayers.length; i++) {
audioPlayers[i].addEventListener('play', function() {
syncSubtitle(this);
});
}