You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中JSON转SRT格式,实现视频读取SRT变量的技术求助

Fix: Load In-Memory SRT Subtitles into HTML5 Video in React

Hey there, let's tackle this fast—you're down to the wire in your hackathon, so let's get your custom subtitles working with the video player right away! 🚀

The Core Problem

The HTML5 <track> element expects a URL for its src attribute, not a raw string. Since you can't write files directly in the browser, we'll convert your SRT string into a temporary Blob URL that the video can read.

Step-by-Step Fix for Your Video Component

Here's the updated Video component with all the necessary changes:

import React, { Component } from 'react';
import TalkingTwins from '../video/TalkingTwins.mp4';

export class Video extends Component {
  constructor(props) {
    super(props);
    this.state = {
      subtitleUrl: undefined,
    };
    // Store the URL reference to clean it up later
    this.subtitleBlobUrl = null;
  }

  componentDidUpdate(prevProps) {
    // Only update if the SRT string actually changes
    if (prevProps.srtString !== this.props.srtString && this.props.srtString) {
      // Clean up old URL first to avoid memory leaks
      if (this.subtitleBlobUrl) {
        URL.revokeObjectURL(this.subtitleBlobUrl);
      }

      // Create a Blob from the SRT string with the correct MIME type
      const srtBlob = new Blob([this.props.srtString], { type: 'application/x-subrip' });
      // Generate a temporary URL for the Blob
      const blobUrl = URL.createObjectURL(srtBlob);

      this.subtitleBlobUrl = blobUrl;
      this.setState({ subtitleUrl: blobUrl });
    }
  }

  componentWillUnmount() {
    // Clean up the Blob URL when the component unmounts
    if (this.subtitleBlobUrl) {
      URL.revokeObjectURL(this.subtitleBlobUrl);
    }
  }

  render() {
    return (
      <div>
        <video controls width="320" height="176">
          <source src={TalkingTwins} type="video/mp4" />
          {/* Only render the track if we have a valid URL */}
          {this.state.subtitleUrl && (
            <track
              src={this.state.subtitleUrl}
              kind="subtitle"
              srclang="en-US"
              label="English"
              default
            />
          )}
          Your browser does not support HTML5 video.
        </video>
      </div>
    );
  }
}

Key Changes Explained

  • Blob URL Generation: We convert your SRT string into a Blob (binary large object) with the MIME type application/x-subrip (standard for SRT files), then use URL.createObjectURL() to generate a temporary browser URL that the <track> can use.
  • Memory Leak Prevention: We store the Blob URL reference and revoke it when the component updates with a new SRT string or unmounts—this is crucial to avoid cluttering the browser's memory.
  • Updated Lifecycle: Replaced the deprecated componentWillReceiveProps with componentDidUpdate, which is the recommended way to handle prop changes in React class components now.
  • Cleaner Render: Removed the unnecessary bool state—we just check if subtitleUrl exists to render the track.

Quick Fix for Your Caption Component

While we're at it, fix the form submission issue in your Caption component (right now, pressing Enter in the input will trigger a page reload):

// In the Caption component's render method, prevent default form submission
<form onSubmit={(e) => e.preventDefault()}>
  <input 
    placeholder="Enter text here" 
    value={caption.text} 
    onChange={(e) => this.onChange(caption.number, e)} 
  />
</form>

How It All Works Together

  1. Your Caption component generates the SRT string and passes it to Video via srtString prop.
  2. Video detects the new prop, converts the string to a Blob URL, and updates the state.
  3. The <track> element uses the Blob URL to load the subtitles directly from memory—no file write required!

You should be good to go now—test it out, and good luck with your hackathon submission! 🎉

内容的提问来源于stack exchange,提问作者Nicholas Hrboka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:43:55