Opsi konfigurasi untuk Live API


Bahkan dengan implementasi dasar untuk Live API, Anda dapat membangun interaksi yang menarik dan efektif bagi pengguna. Anda dapat menyesuaikan pengalaman lebih lanjut menggunakan opsi konfigurasi berikut:



Suara dan bahasa respons

Anda dapat membuat model merespons dengan suara tertentu dan memengaruhi model untuk merespons dalam berbagai bahasa.

Menentukan suara respons

Klik penyedia Gemini API untuk melihat konten dan kode khusus penyedia di halaman ini.

Live API mendukung 30 suara HD yang disintesis, masing-masing dengan karakteristik yang berbeda. Anda dapat melihat daftar opsi suara respons dan mendengarkan demo setiap suara dengan meluaskan bagian di bawah.

Jika Anda tidak menentukan suara respons, defaultnya adalah Puck.

Untuk menentukan suara respons, tetapkan nama suara dalam objek speechConfig sebagai bagian dari konfigurasi model.

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")
    )
);

// ...

Memengaruhi bahasa respons

Model Live API secara otomatis memilih bahasa yang sesuai untuk responsnya.

Jika Anda ingin model merespons dalam bahasa selain bahasa Inggris atau selalu dalam bahasa tertentu, Anda dapat memengaruhi respons model menggunakan system instructions seperti contoh berikut:

  • Memperkuat model bahwa bahasa selain bahasa Inggris mungkin sesuai

    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.
    
  • Memberi tahu model untuk selalu merespons dalam bahasa tertentu

    RESPOND IN LANGUAGE. YOU MUST RESPOND UNMISTAKABLY IN LANGUAGE.
    



Transkripsi untuk input dan output audio

Klik penyedia Gemini API untuk melihat konten dan kode khusus penyedia di halaman ini.

Sebagai bagian dari respons model, Anda dapat menerima transkripsi input audio dan respons audio model. Anda menetapkan konfigurasi ini sebagai bagian dari konfigurasi model.

  • Untuk transkripsi input audio, tambahkan inputAudioTranscription.

  • Untuk transkripsi respons audio model, tambahkan outputAudioTranscription.

Perhatikan hal berikut:

  • Anda dapat mengonfigurasi model untuk menampilkan transkripsi input dan output (seperti yang ditunjukkan dalam contoh berikut), atau Anda dapat mengonfigurasinya untuk menampilkan hanya salah satunya.

  • Transkrip di-streaming bersama dengan audio, jadi sebaiknya kumpulkan transkrip seperti yang Anda lakukan pada bagian teks di setiap giliran.

  • Bahasa transkripsi disimpulkan dari input audio dan respons audio model.

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
}

// ...



Deteksi aktivitas suara (VAD)

Deteksi aktivitas suara (VAD) memungkinkan model mengenali saat seseorang berbicara. Hal ini penting untuk menciptakan percakapan yang alami, karena memungkinkan Anda menyela model kapan saja. VAD diaktifkan secara default.

Anda dapat menyesuaikan perilaku VAD, termasuk menangani gangguan. Atau, Anda dapat menonaktifkan VAD otomatis untuk mengambil kontrol manual sepenuhnya atas giliran percakapan (seperti untuk antarmuka push-to-talk).

Mengonfigurasi deteksi aktivitas suara (VAD)

Klik penyedia Gemini API untuk melihat konten dan kode khusus penyedia di halaman ini.

Contoh berikut menunjukkan cara menyesuaikan perilaku VAD dengan menetapkan realtimeInputConfig sebagai bagian dari konfigurasi model. Pelajari setelan yang tersedia untuk konfigurasi ini dalam tabel di bagian selanjutnya.

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
        )
    )
);

Setelan konfigurasi VAD yang tersedia

Setelan Nilai yang didukung Deskripsi
Deteksi aktivitas otomatis (automaticActivityDetection)
startSensitivity
  • LOW (default)
  • HIGH

Menentukan seberapa cepat server mendeteksi saat pengguna mulai berbicara:

  • LOW: Kurang sensitif terhadap suara samar. Hal ini membantu mencegah suara bising di sekitar memulai giliran bicara secara tidak sengaja.
  • HIGH: Lebih sensitif. Hal ini membantu mendeteksi ucapan yang lebih pelan atau kata-kata yang diucapkan dengan lembut dengan cepat.
endSensitivity
  • LOW (default)
  • HIGH

Menentukan seberapa cepat server mendeteksi saat pengguna berhenti berbicara:

  • LOW: Kurang sensitif terhadap jeda di akhir. Server mengakomodasi keraguan alami atau kata-kata yang lebih tenang di akhir kalimat.
  • HIGH: Lebih sensitif. Server akan segera mengakhiri giliran bicara setelah level suara turun.
prefixPadding Durasi dalam milidetik
(default: Tidak ada (0 ms))

Menentukan jumlah audio yang akan disertakan sebelum ucapan terdeteksi.

Buffer "lihat balik" ini memastikan model menangkap awal ucapan secara penuh, termasuk suku kata pertama yang sering dimulai sebelum detektor dipicu.

  • Nilai default 0 dapat menyebabkan awal kata terpotong.
  • Direkomendasikan: 20-50 milidetik
silenceDuration Durasi dalam milidetik
(default: ~800 md)

Menentukan durasi tunggu server dalam keheningan sebelum mengakhiri giliran bicara. Hal ini menentukan seberapa toleran sistem terhadap jeda alami di tengah kalimat (seperti berpikir, bernapas, atau batas klausa).

  • Direkomendasikan (500-800 md): Memberikan keseimbangan yang baik—model menerima audio yang lengkap dan kaya konteks sekaligus menjaga latensi respons tetap wajar.
  • Terlalu rendah (di bawah 200 md): Mengakhiri giliran bicara selama jeda alami, membagi ucapan menjadi fragmen kecil yang dapat menurunkan kualitas transkripsi dan respons.
  • Terlalu tinggi (di atas 2.000 md): Menambahkan penundaan yang terlihat sebelum model mulai merespons.
Perilaku gangguan (activityHandling)
activityHandling
  • INTERRUPT (default)
  • NO_INTERRUPT

Menentukan cara server menangani aktivitas pengguna yang masuk saat membuat respons:

  • INTERRUPT: Segera membatalkan respons model saat ini saat aktivitas pengguna terdeteksi.
  • NO_INTERRUPT: Terus membuat respons tanpa gangguan.
Cakupan belokan (turnCoverage)
turnCoverage
  • ONLY_ACTIVITY (default)
  • ALL_INPUT
  • AUDIO_ACTIVITY_AND_ALL_VIDEO

Menentukan input yang di-streaming yang disertakan dalam konteks giliran percakapan:

  • ONLY_ACTIVITY: Mengecualikan keheningan, hanya mempertahankan segmen tempat aktivitas pengguna terdeteksi.
  • ALL_INPUT: Mempertahankan semua input yang di-streaming, termasuk audio hening.
  • AUDIO_ACTIVITY_AND_ALL_VIDEO: Mempertahankan semua frame video yang di-streaming, tetapi hanya segmen audio tempat aktivitas terdeteksi.

Menangani gangguan

Jika server mendeteksi ucapan pengguna yang masuk saat model menghasilkan respons dan activityHandling ditetapkan ke INTERRUPT (default), perhatikan perilaku berikut:

  • Pembuatan dibatalkan: Model akan segera menghentikan responsnya dan menghapus panggilan alat yang tertunda.

  • Histori sesi terpotong: Hanya konten yang sudah dikirim ke aplikasi Anda sebelum gangguan yang dipertahankan di jendela konteks sesi.

  • Sinyal gangguan dikeluarkan: Server mengirimkan pesan respons yang menunjukkan bahwa pembuatan terganggu (seperti wasInterrupted di Swift atau interrupted di Kotlin, Java, Web, Flutter, dan Unity).

Menonaktifkan deteksi aktivitas suara (VAD) otomatis

Untuk mengambil kontrol manual penuh atas giliran percakapan (seperti untuk antarmuka push-to-talk), Anda dapat menonaktifkan deteksi aktivitas suara (VAD) otomatis, alih-alih mengonfigurasi parameter sensitivitas.

Jika deteksi otomatis dinonaktifkan, server tidak akan otomatis mendeteksi ucapan atau memicu respons berdasarkan keheningan audio. Sebagai gantinya, aplikasi Anda harus memberi sinyal batas aktivitas pengguna secara manual selama sesi aktif.

1. Menonaktifkan VAD otomatis dalam konfigurasi model

Klik penyedia Gemini API untuk melihat konten dan kode khusus penyedia di halaman ini.

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. Memberi sinyal batas aktivitas pengguna secara manual

Jika Anda menonaktifkan VAD, aplikasi Anda harus secara manual membatasi batas setiap giliran aktivitas pengguna:

  1. Memberi sinyal awal aktivitas: Panggil sendStartActivityRealtime sebelum mengirim data audio (misalnya, saat pengguna menekan tombol push-to-talk).

  2. Streaming input pengguna: Melakukan streaming data audio (atau video) secara terus-menerus menggunakan sendAudioRealtime.

  3. Memberi sinyal akhir aktivitas: Panggil sendStopActivityRealtime saat pengguna selesai berbicara (misalnya, saat pengguna melepaskan tombol push-to-talk). Hal ini menandakan akhir giliran pengguna dan memicu respons model.

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();



Pengelolaan sesi

Pelajari topik terkait sesi berikut: