Các lựa chọn cấu hình cho Live API


Ngay cả khi chỉ triển khai cơ bản cho Live API, bạn vẫn có thể tạo ra các hoạt động tương tác hấp dẫn và mạnh mẽ cho người dùng. Bạn có thể tuỳ chỉnh trải nghiệm nhiều hơn nữa bằng cách sử dụng các tuỳ chọn cấu hình sau:



Giọng nói và ngôn ngữ của câu trả lời

Bạn có thể yêu cầu mô hình trả lời bằng một giọng nói cụ thể và tác động đến mô hình để trả lời bằng nhiều ngôn ngữ.

Chỉ định giọng nói phản hồi

Nhấp vào nhà cung cấp Gemini API của bạn để xem nội dung và mã dành riêng cho nhà cung cấp trên trang này.

Live API hỗ trợ 30 giọng nói HD tổng hợp khác nhau, mỗi giọng nói có đặc điểm riêng biệt. Bạn có thể xem danh sách các lựa chọn giọng nói cho câu trả lời và nghe bản minh hoạ của từng giọng nói bằng cách mở rộng phần bên dưới.

Nếu bạn không chỉ định giọng nói phản hồi, thì giọng nói mặc định sẽ là Puck.

Để chỉ định giọng nói phản hồi, hãy đặt tên giọng nói trong đối tượng speechConfig trong cấu hình mô hình.

Swift


// ...

let liveModel = FirebaseAI.firebaseAI(backend: .googleAI()).liveModel(
  modelName: "GEMINI_LIVE_API_MODEL_NAME",
  // Configure the model to use a specific voice for its audio response.
  generationConfig: LiveGenerationConfig(
    responseModalities: [.audio],
    speech: SpeechConfig(voiceName: "VOICE_NAME")
  )
)

// ...

Kotlin


// ...

val model = Firebase.ai(backend = GenerativeBackend.googleAI()).liveModel(
    modelName = "GEMINI_LIVE_API_MODEL_NAME",
    // Configure the model to use a specific voice for its audio response.
    generationConfig = liveGenerationConfig {
        responseModality = ResponseModality.AUDIO
        speechConfig = SpeechConfig(voice = Voice("VOICE_NAME"))
    }
)

// ...

Java


// ...

LiveGenerativeModel lm = FirebaseAI.getInstance(GenerativeBackend.googleAI()).liveModel(
    "GEMINI_LIVE_API_MODEL_NAME",
    // Configure the model to use a specific voice for its audio response.
    new LiveGenerationConfig.Builder()
        .setResponseModality(ResponseModality.AUDIO)
        .setSpeechConfig(new SpeechConfig(new Voice("VOICE_NAME")))
        .build()
);

// ...

Web


// ...

const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

const liveModel = getLiveGenerativeModel(ai, {
  model: "GEMINI_LIVE_API_MODEL_NAME",
  // Configure the model to use a specific voice for its audio response.
  generationConfig: {
    responseModalities: [ResponseModality.AUDIO],
    speechConfig: {
      voiceConfig: {
        prebuiltVoiceConfig: { voiceName: "VOICE_NAME" },
      },
    },
  },
});

// ...

Dart


// ...

final _liveModel = FirebaseAI.googleAI().liveGenerativeModel(
  model: 'GEMINI_LIVE_API_MODEL_NAME',
  // Configure the model to use a specific voice for its audio response.
  liveGenerationConfig: LiveGenerationConfig(
    responseModalities: [ResponseModalities.audio],
    speechConfig: SpeechConfig(voiceName: 'VOICE_NAME'),
  ),
);

// ...

Unity


// ...

var liveModel = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).GetLiveModel(
    modelName: "GEMINI_LIVE_API_MODEL_NAME",
    // Configure the model to use a specific voice for its audio response
    liveGenerationConfig: new LiveGenerationConfig(
        responseModalities: new[] { ResponseModality.Audio },
        speechConfig: SpeechConfig.UsePrebuiltVoice("VOICE_NAME")
    )
);

// ...

Ảnh hưởng đến ngôn ngữ của câu trả lời

Các mô hình Live API sẽ tự động chọn ngôn ngữ phù hợp cho câu trả lời.

Nếu muốn mô hình phản hồi bằng một ngôn ngữ không phải tiếng Anh hoặc luôn bằng một ngôn ngữ cụ thể, bạn có thể tác động đến câu trả lời của mô hình bằng cách sử dụng chỉ dẫn hệ thống như các ví dụ sau:

  • Củng cố cho mô hình rằng ngôn ngữ không phải tiếng Anh có thể phù hợp

    Listen to the speaker carefully. If you detect a non-English language, respond
    in the language you hear from the speaker. You must respond unmistakably in the
    speaker's language.
    
  • Yêu cầu mô hình luôn trả lời bằng một ngôn ngữ cụ thể

    RESPOND IN LANGUAGE. YOU MUST RESPOND UNMISTAKABLY IN LANGUAGE.
    



Bản chép lời cho đầu vào và đầu ra âm thanh

Nhấp vào nhà cung cấp Gemini API của bạn để xem nội dung và mã dành riêng cho nhà cung cấp trên trang này.

Trong câu trả lời của mô hình, bạn có thể nhận được bản chép lời của đầu vào âm thanh và câu trả lời bằng âm thanh của mô hình. Bạn đặt cấu hình này trong phần cấu hình mô hình.

  • Để chép lời cho dữ liệu âm thanh đầu vào, hãy thêm inputAudioTranscription.

  • Để chép lời câu trả lời dạng âm thanh của mô hình, hãy thêm outputAudioTranscription.

Lưu ý những điều sau:

  • Bạn có thể định cấu hình mô hình để trả về bản chép lời của cả dữ liệu đầu vào và đầu ra (như trong ví dụ sau) hoặc bạn có thể định cấu hình mô hình để chỉ trả về một trong hai.

  • Bản chép lời được truyền trực tuyến cùng với âm thanh, vì vậy, tốt nhất bạn nên thu thập chúng như cách bạn làm với các phần văn bản trong mỗi lượt.

  • Ngôn ngữ của bản chép lời được suy luận từ dữ liệu âm thanh đầu vào và phản hồi âm thanh của mô hình.

Swift


// ...

let liveModel = FirebaseAI.firebaseAI(backend: .googleAI()).liveModel(
  modelName: "GEMINI_LIVE_API_MODEL_NAME",
  // Configure the model to return transcriptions of the audio input and output.
  generationConfig: LiveGenerationConfig(
    responseModalities: [.audio],
    inputAudioTranscription: AudioTranscriptionConfig(),
    outputAudioTranscription: AudioTranscriptionConfig()
  )
)

var inputTranscript: String = ""
var outputTranscript: String = ""

do {
  let session = try await liveModel.connect()
  for try await response in session.responses {
    if case let .content(content) = response.payload {
      if let inputText = content.inputAudioTranscription?.text {
        // Handle transcription text of the audio input.
        inputTranscript += inputText
      }

      if let outputText = content.outputAudioTranscription?.text {
        // Handle transcription text of the audio output.
        outputTranscript += outputText
      }

      if content.isTurnComplete {
        // Log the transcripts after the current turn is complete.
        print("Input audio: \(inputTranscript)")
        print("Output audio: \(outputTranscript)")

        // Reset the transcripts for the next turn.
        inputTranscript = ""
        outputTranscript = ""
      }
    }
  }


} catch {
  // Handle error
}

// ...

Kotlin


// ...

val liveModel = Firebase.ai(backend = GenerativeBackend.googleAI()).liveModel(
    modelName = "GEMINI_LIVE_API_MODEL_NAME",
    // Configure the model to return transcriptions of the audio input and output.
    generationConfig = liveGenerationConfig {
        responseModality = ResponseModality.AUDIO
        inputAudioTranscription = AudioTranscriptionConfig()
        outputAudioTranscription = AudioTranscriptionConfig()
   }
)

val liveSession = liveModel.connect()

fun handleTranscription(input: Transcription?, output: Transcription?) {
    input?.text?.let { text ->
        // Handle transcription text of the audio input.
        println("Input Transcription: $text")
    }
    output?.text?.let { text ->
        // Handle transcription text of the audio output.
        println("Output Transcription: $text")
    }
}

liveSession.startAudioConversation(null, ::handleTranscription)

// ...

Java


// ...

ExecutorService executor = Executors.newFixedThreadPool(1);

LiveGenerativeModel lm = FirebaseAI.getInstance(GenerativeBackend.googleAI()).liveModel(
    "GEMINI_LIVE_API_MODEL_NAME",
    // Configure the model to return transcriptions of the audio input and output.
    new LiveGenerationConfig.Builder()
            .setResponseModality(ResponseModality.AUDIO)
            .setInputAudioTranscription(new AudioTranscriptionConfig())
            .setOutputAudioTranscription(new AudioTranscriptionConfig())
            .build()
    );

LiveModelFutures liveModel = LiveModelFutures.from(lm);
ListenableFuture<LiveSessionFutures> sessionFuture = liveModel.connect();

Futures.addCallback(sessionFuture, new FutureCallback<LiveSessionFutures>() {
    @Override
    public void onSuccess(LiveSessionFutures ses) {
        LiveSessionFutures session = ses;
        session.startAudioConversation((Transcription input, Transcription output) -> {
            if (input != null) {
                // Handle transcription text of the audio input.
                System.out.println("Input Transcription: " + input.getText());
            }
            if (output != null) {
                // Handle transcription text of the audio output.
                System.out.println("Output Transcription: " + output.getText());
            }
            return null;
        });
    }

    @Override
    public void onFailure(Throwable t) {
        // Handle exceptions
        t.printStackTrace();
    }
}, executor);

// ...

Web


// ...

const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

const liveModel = getLiveGenerativeModel(ai, {
  model: 'GEMINI_LIVE_API_MODEL_NAME',
  // Configure the model to return transcriptions of the audio input and output.
  generationConfig: {
    responseModalities: [ResponseModality.AUDIO],
    inputAudioTranscription: {},
    outputAudioTranscription: {},
  },
});

const liveSession = await liveModel.connect();

liveSession.sendAudioRealtime({ data, mimeType: "audio/pcm" });

const messages = liveSession.receive();
for await (const message of messages) {
  switch (message.type) {
    case 'serverContent':
      if (message.inputTranscription) {
        // Handle transcription text of the audio input.
        console.log(`Input transcription: ${message.inputTranscription.text}`);
      }
      if (message.outputTranscription) {
        // Handle transcription text of the audio output.
        console.log(`Output transcription: ${message.outputTranscription.text}`);
      } else {
      	 // Handle other message types (modelTurn, turnComplete, interruption).
      }
    default:
      // Handle other message types (toolCall, toolCallCancellation).
  }
}

// ...

Dart


// ...

final _liveModel = FirebaseAI.googleAI().liveGenerativeModel(
  model: 'GEMINI_LIVE_API_MODEL_NAME',
  // Configure the model to return transcriptions of the audio input and output.
  liveGenerationConfig: LiveGenerationConfig(
    responseModalities: [ResponseModalities.audio],
    inputAudioTranscription: AudioTranscriptionConfig(),
    outputAudioTranscription: AudioTranscriptionConfig(),
  ),
);

final LiveSession _session = await _liveModel.connect();

await for (final response in _session.receive()) {
  if (response.message case LiveServerContent message) {
    if (message.inputTranscription?.text case final inputText?) {
      // Handle transcription text of the audio input.
      print('Input: $inputText');
    }

    if (message.outputTranscription?.text case final outputText?) {
      // Handle transcription text of the audio output.
      print('Output: $outputText');
    }
  }
}

// ...

Unity


// ...

var liveModel = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).GetLiveModel(
    modelName: "GEMINI_LIVE_API_MODEL_NAME",
    // Configure the model to return transcriptions of the audio input and output
    liveGenerationConfig: new LiveGenerationConfig(
        responseModalities: new[] { ResponseModality.Audio },
        inputAudioTranscription: new AudioTranscriptionConfig(),
        outputAudioTranscription: new AudioTranscriptionConfig()
    )
);

try
{
    var session = await liveModel.ConnectAsync();
    var stream = session.ReceiveAsync();
    await foreach (var response in stream) {
        if (response.Message is LiveSessionContent sessionContent) {
            if (!string.IsNullOrEmpty(sessionContent.InputTranscription?.Text)) {
              // handle transcription text of input audio
            }

            if (!string.IsNullOrEmpty(sessionContent.OutputTranscription?.Text)) {
              // handle transcription text of output audio
            }
        }
    }
}
catch (Exception e)
{
    // Handle error
}

// ...



Phát hiện hoạt động giọng nói (VAD)

Tính năng phát hiện hoạt động giọng nói (VAD) giúp mô hình nhận ra khi có người đang nói. Điều này rất cần thiết để tạo ra các cuộc trò chuyện tự nhiên, vì nó cho phép bạn ngắt lời mô hình bất cứ lúc nào. VAD được bật theo mặc định.

Bạn có thể tuỳ chỉnh hành vi của VAD, bao gồm cả việc xử lý các trường hợp gián đoạn. Bạn cũng có thể tắt tính năng VAD tự động để kiểm soát hoàn toàn theo cách thủ công các lượt trò chuyện (chẳng hạn như đối với giao diện nhấn để nói).

Định cấu hình tính năng phát hiện hoạt động giọng nói (VAD)

Nhấp vào nhà cung cấp Gemini API của bạn để xem nội dung và mã dành riêng cho nhà cung cấp trên trang này.

Ví dụ sau đây cho thấy cách bạn có thể tuỳ chỉnh hành vi của VAD bằng cách đặt realtimeInputConfig trong cấu hình mô hình. Tìm hiểu về các chế độ cài đặt có sẵn cho cấu hình này trong bảng ở phần sau của mục này.

Swift


// ...

let liveModel = FirebaseAI.firebaseAI(backend: .googleAI()).liveModel(
  modelName: "GEMINI_LIVE_API_MODEL_NAME",
  generationConfig: LiveGenerationConfig(
    responseModalities: [.audio],
    // Configure voice activity detection (VAD), interruption handling, and turn coverage.
    // IMPORTANT: Example values shown here. Make sure to update for your use case.
    realtimeInputConfig: RealtimeInputConfig(
      automaticActivityDetection: ActivityDetectionConfig(
        startSensitivity: .low,
        endSensitivity: .low,
        prefixPadding: .milliseconds(20),
        silenceDuration: .milliseconds(500)
      ),
      activityHandling: .interrupt,
      turnCoverage: .onlyActivity
    )
  )
)

Kotlin


// ...

val liveModel = Firebase.ai(backend = GenerativeBackend.googleAI()).liveModel(
    modelName = "GEMINI_LIVE_API_MODEL_NAME",
    generationConfig = liveGenerationConfig {
        responseModality = ResponseModality.AUDIO
        // Configure voice activity detection (VAD), interruption handling, and turn coverage.
        // IMPORTANT: Example values shown here. Make sure to update for your use case.
        realtimeInputConfig = realtimeInputConfig {
            automaticActivityDetection = ActivityDetectionConfig.builder()
                .setStartSensitivity(ActivityDetectionConfig.Sensitivity.LOW)
                .setEndSensitivity(ActivityDetectionConfig.Sensitivity.LOW)
                .setPrefixPaddingMs(20)
                .setSilenceDurationMs(500)
                .build()
            activityHandling = RealtimeInputConfig.ActivityHandling.INTERRUPT
            turnCoverage = RealtimeInputConfig.TurnCoverage.ONLY_ACTIVITY
        }
    }
)

Java


// ...

LiveGenerativeModel lm = FirebaseAI.getInstance(GenerativeBackend.googleAI()).liveModel(
        "GEMINI_LIVE_API_MODEL_NAME",
        new LiveGenerationConfig.Builder()
                .setResponseModality(ResponseModality.AUDIO)
                // Configure voice activity detection (VAD), interruption handling, and turn coverage.
                // IMPORTANT: Example values shown here. Make sure to update for your use case.
                .setRealtimeInputConfig(RealtimeInputConfig.builder()
                        .setAutomaticActivityDetection(ActivityDetectionConfig.builder()
                                .setStartSensitivity(ActivityDetectionConfig.Sensitivity.LOW)
                                .setEndSensitivity(ActivityDetectionConfig.Sensitivity.LOW)
                                .setPrefixPaddingMs(20)
                                .setSilenceDurationMs(500)
                                .build())
                        .setActivityHandling(RealtimeInputConfig.ActivityHandling.INTERRUPT)
                        .setTurnCoverage(RealtimeInputConfig.TurnCoverage.ONLY_ACTIVITY)
                        .build())
                .build()
);

Web

Not yet supported for Web apps - check back soon!

Dart


// ...

final _liveModel = FirebaseAI.googleAI().liveGenerativeModel(
  model: 'GEMINI_LIVE_API_MODEL_NAME',
  liveGenerationConfig: LiveGenerationConfig(
    responseModalities: [ResponseModalities.audio],
    // Configure voice activity detection (VAD), interruption handling, and turn coverage.
    // IMPORTANT: Example values shown here. Make sure to update for your use case.
    realtimeInputConfig: RealtimeInputConfig(
      automaticActivityDetection: ActivityDetectionConfig(
        startSensitivity: Sensitivity.low,
        endSensitivity: Sensitivity.low,
        prefixPaddingMS: 20,
        silenceDurationMS: 500,
      ),
      activityHandling: ActivityHandling.interrupt,
      turnCoverage: TurnCoverage.onlyActivity,
    ),
  ),
);

Unity


// ...

var liveModel = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).GetLiveModel(
    modelName: "GEMINI_LIVE_API_MODEL_NAME",
    liveGenerationConfig: new LiveGenerationConfig(
        responseModalities: new[] { ResponseModality.Audio },
        // Configure voice activity detection (VAD), interruption handling, and turn coverage.
        // IMPORTANT: Example values shown here. Make sure to update for your use case.
        realtimeInputConfig: new RealtimeInputConfig(
            automaticActivityDetection: new ActivityDetectionConfig(
                startSensitivity: ActivityDetectionConfig.Sensitivity.Low,
                endSensitivity: ActivityDetectionConfig.Sensitivity.Low,
                prefixPaddingMS: 20,
                silenceDurationMS: 500
            ),
            activityHandling: RealtimeInputConfig.ActivityHandling.Interrupt,
            turnCoverage: RealtimeInputConfig.TurnCoverage.OnlyActivity
        )
    )
);

Các chế độ cài đặt hiện có cho tính năng VAD

Cài đặt Giá trị được hỗ trợ Mô tả
Tự động phát hiện hoạt động (automaticActivityDetection)
startSensitivity
  • LOW (mặc định)
  • HIGH

Xác định mức độ dễ dàng mà máy chủ phát hiện khi người dùng bắt đầu nói:

  • LOW: Ít nhạy hơn với âm thanh nhỏ. Điều này giúp ngăn tiếng ồn xung quanh vô tình bắt đầu một lượt nói.
  • HIGH: Nhạy hơn. Điều này giúp nhanh chóng phát hiện lời nói nhỏ hoặc lời nói nhẹ nhàng.
endSensitivity
  • LOW (mặc định)
  • HIGH

Xác định mức độ dễ dàng mà máy chủ phát hiện khi người dùng ngừng nói:

  • LOW: Ít nhạy cảm hơn với các khoảng tạm dừng ở cuối. Máy chủ cho phép người dùng ngập ngừng tự nhiên hoặc nói nhỏ hơn ở cuối câu.
  • HIGH: Nhạy hơn. Máy chủ sẽ kết thúc lượt nói ngay khi âm lượng giọng nói giảm xuống.
prefixPadding Thời lượng tính bằng mili giây
(mặc định: Không có (0 mili giây))

Xác định lượng âm thanh cần đưa vào trước khi phát hiện thấy lời nói.

Bộ đệm "nhìn lại" này đảm bảo mô hình ghi lại toàn bộ thời điểm bắt đầu lời nói, bao gồm cả âm tiết đầu tiên thường bắt đầu trước khi bộ phát hiện kích hoạt.

  • Giá trị mặc định của 0 có thể khiến phần đầu của từ bị cắt bớt.
  • Nên dùng: 20 – 50 mili giây
silenceDuration Thời lượng tính bằng mili giây
(mặc định: ~800 mili giây)

Xác định thời gian máy chủ chờ trong khoảng lặng trước khi kết thúc một lượt nói. Thuộc tính này xác định mức độ chấp nhận của hệ thống đối với các khoảng dừng tự nhiên giữa câu (chẳng hạn như suy nghĩ, thở hoặc ranh giới mệnh đề).

  • Nên dùng (500 – 800 mili giây): Mang lại sự cân bằng tốt – mô hình nhận được âm thanh hoàn chỉnh, giàu ngữ cảnh trong khi vẫn duy trì độ trễ phản hồi hợp lý.
  • Quá thấp (dưới 200 mili giây): Kết thúc lượt nói trong những khoảng dừng tự nhiên, chia lời nói thành các đoạn nhỏ có thể làm giảm chất lượng của bản chép lời và câu trả lời.
  • Quá cao (trên 2000 mili giây): Thêm độ trễ đáng kể trước khi mô hình bắt đầu phản hồi.
Hành vi gián đoạn (activityHandling)
activityHandling
  • INTERRUPT (mặc định)
  • NO_INTERRUPT

Xác định cách máy chủ xử lý hoạt động của người dùng trong khi tạo phản hồi:

  • INTERRUPT: Huỷ ngay câu trả lời hiện tại của mô hình khi phát hiện hoạt động của người dùng.
  • NO_INTERRUPT: Tiếp tục tạo câu trả lời mà không bị gián đoạn.
Phạm vi bao phủ của bối cảnh rẽ (turnCoverage)
turnCoverage
  • ONLY_ACTIVITY (mặc định)
  • ALL_INPUT
  • AUDIO_ACTIVITY_AND_ALL_VIDEO

Xác định dữ liệu đầu vào được truyền trực tuyến nào được đưa vào bối cảnh lượt trò chuyện:

  • ONLY_ACTIVITY: Loại trừ khoảng lặng, chỉ giữ lại các phân đoạn phát hiện thấy hoạt động của người dùng.
  • ALL_INPUT: Giữ lại tất cả dữ liệu đầu vào được truyền trực tuyến, bao gồm cả âm thanh im lặng.
  • AUDIO_ACTIVITY_AND_ALL_VIDEO: Giữ lại tất cả khung hình video được phát trực tuyến, nhưng chỉ giữ lại các đoạn âm thanh có hoạt động được phát hiện.

Xử lý hoạt động gây gián đoạn

Nếu máy chủ phát hiện thấy lời nói của người dùng trong khi mô hình đang tạo câu trả lời và activityHandling được đặt thành INTERRUPT (mặc định), hãy lưu ý các hành vi sau:

  • Quá trình tạo bị huỷ: Mô hình ngay lập tức dừng phản hồi và huỷ mọi lệnh gọi công cụ đang chờ xử lý.

  • Nhật ký phiên bị cắt bớt: Chỉ nội dung đã được truyền đến ứng dụng của bạn trước khi bị gián đoạn mới được giữ lại trong cửa sổ ngữ cảnh của phiên.

  • Tín hiệu gián đoạn được phát ra: Máy chủ gửi một thông báo phản hồi cho biết quá trình tạo đã bị gián đoạn (chẳng hạn như wasInterrupted trong Swift hoặc interrupted trong Kotlin, Java, Web, Flutter và Unity).

Tắt tính năng tự động phát hiện hoạt động giọng nói (VAD)

Để hoàn toàn kiểm soát lượt trò chuyện theo cách thủ công (chẳng hạn như đối với giao diện nhấn để nói), bạn có thể tắt tính năng tự động phát hiện hoạt động giọng nói (VAD) thay vì định cấu hình các tham số độ nhạy.

Khi bạn tắt tính năng tự động phát hiện, máy chủ sẽ không tự động phát hiện lời nói hoặc kích hoạt phản hồi dựa trên khoảng lặng âm thanh. Thay vào đó, ứng dụng của bạn phải báo hiệu ranh giới hoạt động của người dùng theo cách thủ công trong phiên hoạt động.

1. Tắt tính năng VAD tự động trong cấu hình mô hình

Nhấp vào nhà cung cấp Gemini API của bạn để xem nội dung và mã dành riêng cho nhà cung cấp trên trang này.

Swift


// ...

let liveModel = FirebaseAI.firebaseAI(backend: .googleAI()).liveModel(
  modelName: "GEMINI_LIVE_API_MODEL_NAME",
  generationConfig: LiveGenerationConfig(
    responseModalities: [.audio],
    // Disable automatic voice activity detection (VAD).
    realtimeInputConfig: RealtimeInputConfig(
      automaticActivityDetection: .disabled()
    )
  )
)

Kotlin


// ...

val liveModel = Firebase.ai(backend = GenerativeBackend.googleAI()).liveModel(
    modelName = "GEMINI_LIVE_API_MODEL_NAME",
    generationConfig = liveGenerationConfig {
        responseModality = ResponseModality.AUDIO
        // Disable automatic voice activity detection (VAD).
        realtimeInputConfig = realtimeInputConfig {
            automaticActivityDetection = ActivityDetectionConfig.disabled()
        }
    }
)

Java


// ...

LiveGenerativeModel lm = FirebaseAI.getInstance(GenerativeBackend.googleAI()).liveModel(
        "GEMINI_LIVE_API_MODEL_NAME",
        new LiveGenerationConfig.Builder()
                .setResponseModality(ResponseModality.AUDIO)
                // Disable automatic voice activity detection (VAD).
                .setRealtimeInputConfig(RealtimeInputConfig.builder()
                        .setAutomaticActivityDetection(ActivityDetectionConfig.disabled())
                        .build())
                .build()
);

Web

Not yet supported for Web apps - check back soon!

Dart


// ...

final _liveModel = FirebaseAI.googleAI().liveGenerativeModel(
  model: 'GEMINI_LIVE_API_MODEL_NAME',
  liveGenerationConfig: LiveGenerationConfig(
    responseModalities: [ResponseModalities.audio],
    // Disable automatic voice activity detection (VAD).
    realtimeInputConfig: RealtimeInputConfig(
      automaticActivityDetection: ActivityDetectionConfig.disabled(),
    ),
  ),
);

Unity


// ...

var liveModel = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).GetLiveModel(
    modelName: "GEMINI_LIVE_API_MODEL_NAME",
    liveGenerationConfig: new LiveGenerationConfig(
        responseModalities: new[] { ResponseModality.Audio },
        // Disable automatic voice activity detection (VAD).
        realtimeInputConfig: new RealtimeInputConfig(
            automaticActivityDetection: ActivityDetectionConfig.Disabled()
        )
    )
);

2. Báo hiệu ranh giới hoạt động của người dùng theo cách thủ công

Nếu tắt VAD, ứng dụng của bạn phải phân định ranh giới của từng lượt hoạt động của người dùng theo cách thủ công:

  1. Báo hiệu bắt đầu hoạt động: Gọi sendStartActivityRealtime trước khi gửi dữ liệu âm thanh (ví dụ: khi người dùng nhấn nút nhấn để nói).

  2. Truyền dữ liệu đầu vào của người dùng: Liên tục truyền dữ liệu âm thanh (hoặc video) bằng sendAudioRealtime.

  3. Báo hiệu kết thúc hoạt động: Gọi sendStopActivityRealtime khi người dùng nói xong (ví dụ: khi người dùng thả nút nhấn để nói). Điều này báo hiệu kết thúc lượt của người dùng và kích hoạt phản hồi của mô hình.

Swift

// If you disable automatic voice activity detection (VAD), you need to manually demarcate user activity.

// Signal the start of user activity (for example, on push-to-talk button press).
await session.sendStartActivityRealtime()

// Stream user audio data while the user speaks.
await session.sendAudioRealtime(audioData)

// Signal the end of user activity (for example, on button release) to trigger model response.
await session.sendStopActivityRealtime()

Kotlin

// If you disable automatic voice activity detection (VAD), you need to manually demarcate user activity.

// Signal the start of user activity (for example, on push-to-talk button press).
session.sendStartActivityRealtime()

// Stream user audio data while the user speaks.
session.sendAudioRealtime(audioData)

// Signal the end of user activity (for example, on button release) to trigger model response.
session.sendStopActivityRealtime()

Java

// If you disable automatic voice activity detection (VAD), you need to manually demarcate user activity.

// Signal the start of user activity (for example, on push-to-talk button press).
session.sendStartActivityRealtime();

// Stream user audio data while the user speaks.
session.sendAudioRealtime(audioData);

// Signal the end of user activity (for example, on button release) to trigger model response.
session.sendStopActivityRealtime();

Web

Not yet supported for Web apps - check back soon!

Dart

// If you disable automatic voice activity detection (VAD), you need to manually demarcate user activity.

// Signal the start of user activity (for example, on push-to-talk button press).
await session.sendStartActivityRealtime();

// Stream user audio data while the user speaks.
await session.sendAudioRealtime(audioData);

// Signal the end of user activity (for example, on button release) to trigger model response.
await session.sendStopActivityRealtime();

Unity

// If you disable automatic voice activity detection (VAD), you need to manually demarcate user activity.

// Signal the start of user activity (for example, on push-to-talk button press).
await session.SendStartActivityRealtimeAsync();

// Stream user audio data while the user speaks.
await session.SendAudioRealtimeAsync(audio: audioData);

// Signal the end of user activity (for example, on button release) to trigger model response.
await session.SendStopActivityRealtimeAsync();



Quản lý phiên

Tìm hiểu về các chủ đề sau đây liên quan đến phiên: