使用 Gemini API 分析影片檔案

您可以要求 Gemini 模型分析您提供的影片檔案,無論是內嵌 (base64 編碼) 或透過網址提供皆可。使用 Firebase AI Logic 時,您可以直接從應用程式提出這項要求。

這項功能可讓您執行下列操作:

  • 為影片加上字幕及回答相關問題
  • 使用時間戳記分析影片的特定片段
  • 處理音軌和影像影格,轉錄影片內容
  • 描述、分割及擷取影片中的資訊,包括音軌和視覺影格

本指南說明如何根據影片輸入內容生成文字,但您也可以根據影片輸入內容生成圖片。

跳至程式碼範例 跳至串流回應的程式碼


查看其他指南,瞭解更多影片處理選項
生成結構化輸出內容 多輪對話 生成圖片

事前準備

按一下您的Gemini API供應商,即可在這個頁面查看供應商專屬內容和程式碼。

如果尚未完成入門指南,請先完成。該指南說明如何設定 Firebase 專案、將應用程式連結至 Firebase、新增 SDK、為所選 Gemini API 供應商初始化後端服務,以及建立 GenerativeModel 執行個體。

如要測試及反覆調整提示,建議使用 Google AI Studio。

支援這項功能的模型

本指南說明如何根據影片輸入內容生成文字,適用於下列 Gemini 模型:

  • gemini-4-argon
  • gemini-3.8-flash (以及舊版 gemini-3.7-flash、gemini-3.6-flash 和 gemini-3.5-flash)
  • gemini-3.5-flash-lite (以及舊版 gemini-3.1-flash-lite)

gemini-3.1-pro-preview 和一般用途 Gemini 2.5 模型 (已淘汰) 也支援這項功能。

從影片檔案生成文字 (Base64 編碼)

嘗試這個範例前,請先完成本指南的「事前準備」一節,設定專案和應用程式。
在該節中,您也需要點選所選Gemini API供應商的按鈕,這樣這個頁面才會顯示供應商專屬內容。

您可以透過文字和影片提示,要求 Gemini 模型生成文字,並提供每個輸入檔案的 mimeType 和檔案本身。請參閱本頁後續章節,瞭解輸入檔案的規定和建議。

請注意,這個範例顯示的是提供內嵌檔案,但 SDK 也支援提供 YouTube 網址。

Swift

您可以呼叫 generateContent(),從文字和影片檔案的多模態輸入內容生成文字。


import FirebaseAILogic

// Initialize the Gemini Developer API backend service.
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Create a `GenerativeModel` instance with a model that supports your use case.
let model = ai.generativeModel(modelName: "gemini-3.8-flash")


// Provide the video as `Data` with the appropriate MIME type.
let video = InlineDataPart(data: try Data(contentsOf: videoURL), mimeType: "video/mp4")

// Provide a text prompt to include with the video
let prompt = "What is in the video?"

// To generate text output, call generateContent with the text and video
let response = try await model.generateContent(video, prompt)
print(response.text ?? "No text in response.")

Kotlin

您可以呼叫 generateContent(),從文字和影片檔案的多模態輸入內容生成文字。

在 Kotlin 中,這個 SDK 的方法是暫停函式,必須從協同程式範圍呼叫。

// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
                        .generativeModel("gemini-3.8-flash")


val contentResolver = applicationContext.contentResolver
contentResolver.openInputStream(videoUri).use { stream ->
  stream?.let {
    val bytes = stream.readBytes()

    // Provide a prompt that includes the video specified above and text
    val prompt = content {
        inlineData(bytes, "video/mp4")
        text("What is in the video?")
    }

    // To generate text output, call generateContent with the prompt
    val response = model.generateContent(prompt)
    Log.d(TAG, response.text ?: "")
  }
}

Java

您可以呼叫 generateContent(),從文字和影片檔案的多模態輸入內容生成文字。

如果是 Java,這個 SDK 中的方法會傳回 ListenableFuture。

// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
        .generativeModel("gemini-3.8-flash");

// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);


ContentResolver resolver = getApplicationContext().getContentResolver();
try (InputStream stream = resolver.openInputStream(videoUri)) {
    File videoFile = new File(new URI(videoUri.toString()));
    int videoSize = (int) videoFile.length();
    byte[] videoBytes = new byte[videoSize];
    if (stream != null) {
        stream.read(videoBytes, 0, videoBytes.length);
        stream.close();

        // Provide a prompt that includes the video specified above and text
        Content prompt = new Content.Builder()
                .addInlineData(videoBytes, "video/mp4")
                .addText("What is in the video?")
                .build();

        // To generate text output, call generateContent with the prompt
        ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
        Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
            @Override
            public void onSuccess(GenerateContentResponse result) {
                String resultText = result.getText();
                System.out.println(resultText);
            }

            @Override
            public void onFailure(Throwable t) {
                t.printStackTrace();
            }
        }, executor);
    }
} catch (IOException e) {
    e.printStackTrace();
} catch (URISyntaxException e) {
    e.printStackTrace();
}

Web

您可以呼叫 generateContent(),從文字和影片檔案的多模態輸入內容生成文字。


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";

// TODO(developer): Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Create a `GenerativeModel` instance with a model that supports your use case.
const model = getGenerativeModel(ai, { model: "gemini-3.8-flash" });


// Converts a File object to a Part object.
async function fileToGenerativePart(file) {
  const base64EncodedDataPromise = new Promise((resolve) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result.split(',')[1]);
    reader.readAsDataURL(file);
  });
  return {
    type: "inlineData",
    inlineData: { data: await base64EncodedDataPromise, mimeType: file.type },
  };
}

async function run() {
  // Provide a text prompt to include with the video
  const prompt = "What do you see?";

  const fileInputEl = document.querySelector("input[type=file]");
  const videoPart = await fileToGenerativePart(fileInputEl.files[0]);

  // To generate text output, call generateContent with the text and video
  const result = await model.generateContent([prompt, videoPart]);

  const response = result.response;
  const text = response.text();
  console.log(text);
}

run();

Dart

您可以呼叫 generateContent(),從文字和影片檔案的多模態輸入內容生成文字。


import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';

// Initialize FirebaseApp
await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);

// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
final model =
      FirebaseAI.googleAI().generativeModel(model: 'gemini-3.8-flash');


// Provide a text prompt to include with the video
final prompt = TextPart("What's in the video?");

// Prepare video for input
final video = await File('video0.mp4').readAsBytes();

// Provide the video as `Data` with the appropriate mimetype
final videoPart = InlineDataPart('video/mp4', video);

// To generate text output, call generateContent with the text and images
final response = await model.generateContent([
  Content.multi([prompt, videoPart])
]);
print(response.text);

Unity

您可以呼叫 GenerateContentAsync(),從文字和影片檔案的多模態輸入內容生成文字。


using Firebase;
using Firebase.AI;

// Initialize the Gemini Developer API backend service.
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Create a `GenerativeModel` instance with a model that supports your use case.
var model = ai.GetGenerativeModel(modelName: "gemini-3.8-flash");


// Provide the video as `data` with the appropriate MIME type.
var video = ModelContent.InlineData("video/mp4",
      System.IO.File.ReadAllBytes(System.IO.Path.Combine(
          UnityEngine.Application.streamingAssetsPath, "yourVideo.mp4")));

// Provide a text prompt to include with the video
var prompt = ModelContent.Text("What is in the video?");

// To generate text output, call GenerateContentAsync with the text and video
var response = await model.GenerateContentAsync(new [] { video, prompt });
UnityEngine.Debug.Log(response.Text ?? "No text in response.");

瞭解如何根據用途和應用程式,選擇模型 。

逐句回覆

嘗試這個範例前,請先完成本指南的「事前準備」一節,設定專案和應用程式。
在該節中,您也需要點選所選Gemini API供應商的按鈕,這樣這個頁面才會顯示供應商專屬內容。

您不必等待模型生成完整結果,而是使用串流處理部分結果,加快互動速度。如要串流回覆,請呼叫 generateContentStream。



輸入影片檔案的規定和建議

請注意,以內嵌資料形式提供的檔案在傳輸過程中會編碼為 base64,這會增加要求的大小。如果要求過大,您會收到 HTTP 413 錯誤。

請參閱「支援的輸入檔案和相關規定」頁面,進一步瞭解下列事項:

支援的影片 MIME 類型

Gemini 多模態模型支援下列影片 MIME 類型:

  • FLV - video/x-flv
  • MOV - video/quicktime
  • MPEG - video/mpeg
  • MPEGPS - video/mpegps
  • 每加侖英里數 - video/mpg
  • MP4 - video/mp4
  • WEBM - video/webm
  • WMV - video/wmv
  • 3GPP - video/3gpp

每項要求的限制

每項要求的檔案數量上限:10 個影片檔案



你還可以做些什麼?

試用其他功能

瞭解如何控管內容生成

您也可以使用 Google AI Studio 測試提示和模型設定,甚至取得生成的程式碼片段。

進一步瞭解支援的模型

瞭解適用於各種用途的模型,以及配額和定價。


提供「Firebase AI Logic」使用體驗的意見回饋