Firebase AI Logic을 사용하여 Gemini Live API 시작하기


Gemini Live APIGemini 모델과의 지연 시간이 짧은 실시간 음성 및 동영상 상호작용을 지원하며, 이 모델은 양방향입니다.

Live API와 특수 모델 제품군은 오디오, 동영상 또는 텍스트의 연속 스트림 을 처리하여 즉각적이고 사람과 유사한 음성 대답을 제공하고 사용자에게 자연스러운 대화 환경을 제공할 수 있습니다.

이 페이지에서는 가장 일반적인 기능인 스트리밍 오디오 입력 및 출력을 시작하는 방법을 설명하지만 Live API는 다양한 기능구성 옵션을 지원합니다.

Live API는 WebSocket 연결을 만들어 클라이언트와 Gemini 서버 간에 세션을 설정하는 스테이트풀(Stateful) API입니다. 자세한 내용은 Live API 참조 문서 (Gemini Developer API | Agent Platform Gemini API (formerly Vertex AI))를 참고하세요.

코드 샘플로 이동

유용한 리소스 확인

시작하기 전에

아직 시작 가이드를 완료하지 않았다면 시작 가이드를 완료하세요. 시작 가이드에서는 Firebase 프로젝트를 설정하고, 앱을 Firebase에 연결하고, SDK를 추가하고, 선택한 Gemini API 제공업체의 백엔드 서비스를 초기화하고, LiveModel 인스턴스를 만드는 방법을 설명합니다.

프롬프트와 Live API을(를) 사용하여 Google AI Studio 또는 Agent  Studio에서 프로토타입을 만들 수 있습니다.

이 기능을 지원하는 모델

  • 3.x 모델

    • Gemini Developer API

      • gemini-3.1-flash-live-preview

      이 모델은 미리보기 모델이지만 Gemini Developer API의 "무료 등급" 에서 사용할 수 있습니다.

    • Agent Platform Gemini API (formerly Vertex AI)

      Gemini Live 3.x 모델은 지원되지 않음

  • 2.5 모델

    모델 이름은 Gemini API 제공업체에 따라 다르지만 모델의 기능은 동일합니다.

    • Gemini Developer API

      • gemini-2.5-flash-native-audio-preview-12-2025
      • gemini-2.5-flash-native-audio-preview-09-2025

      이 모델은 미리보기 모델이지만 Gemini Developer API의 '무료 등급' 에서 사용할 수 있습니다.

    • Agent Platform Gemini API (formerly Vertex AI)

      • gemini-live-2.5-flash-native-audio (2025년 12월 출시)
      • gemini-live-2.5-flash-preview-native-audio-09-2025

      Agent Platform Gemini API (formerly Vertex AI)를 사용하는 경우 Live API 모델은 지원되지않습니다global 위치에서.

오디오 입력 및 출력 스트리밍

Gemini API 제공업체를 클릭하여 이 페이지에서 제공업체별 콘텐츠 및 코드를 확인합니다.

다음 예에서는 스트리밍된 오디오 입력 을 전송하고 스트리밍된 오디오 출력 을 수신하는 기본 구현 을 보여줍니다.

Live API의 추가 옵션 및 기능은 이 페이지의 뒷부분에 있는 '또 뭘 할 수 있니?' 섹션을 참고하세요.

Swift

Live API를 사용하려면 LiveModel 인스턴스를 만들고 응답 모드audio로 설정합니다.


import FirebaseAILogic

// Initialize the Gemini Developer API backend service.
// Create a `liveModel` instance with a model that supports the Live API.
let liveModel = FirebaseAI.firebaseAI(backend: .googleAI()).liveModel(
  modelName: "gemini-2.5-flash-native-audio-preview-12-2025",
  // Configure the model to respond with audio.
  generationConfig: LiveGenerationConfig(
    responseModalities: [.audio]
  )
)

do {
  let session = try await liveModel.connect()

  // Load the audio file, or tap a microphone.
  guard let audioFile = NSDataAsset(name: "audio.pcm") else {
    fatalError("Failed to load audio file")
  }

  // Provide the audio data.
  await session.sendAudioRealtime(audioFile.data)

  var outputText = ""
  for try await message in session.responses {
    if case let .content(content) = message.payload {
      content.modelTurn?.parts.forEach { part in
        if let part = part as? InlineDataPart, part.mimeType.starts(with: "audio/pcm") {
          // Handle 16bit pcm audio data at 24khz
          playAudio(part.data)
        }
      }
      // Optional: if you don't need to send more requests.
      if content.isTurnComplete {
        await session.close()
      }
    }
  }
} catch {
  fatalError(error.localizedDescription)
}

Kotlin

Live API를 사용하려면 LiveModel 인스턴스를 만들고 응답 모드AUDIO로 설정합니다.


// Initialize the Gemini Developer API backend service.
// Create a `liveModel` instance with a model that supports the Live API.
val liveModel = Firebase.ai(backend = GenerativeBackend.googleAI()).liveModel(
    modelName = "gemini-2.5-flash-native-audio-preview-12-2025",
    // Configure the model to respond with audio.
    generationConfig = liveGenerationConfig {
        responseModality = ResponseModality.AUDIO
   }
)

val session = liveModel.connect()

// This is the recommended approach.
// However, you can create your own recorder and handle the stream.
session.startAudioConversation()

Java

Live API를 사용하려면 LiveModel 인스턴스를 만들고 응답 모드AUDIO로 설정합니다.


ExecutorService executor = Executors.newFixedThreadPool(1);
// Initialize the Gemini Developer API backend service.
// Create a `liveModel` instance with a model that supports the Live API.
LiveGenerativeModel lm = FirebaseAI.getInstance(GenerativeBackend.googleAI()).liveModel(
        "gemini-2.5-flash-native-audio-preview-12-2025",
        // Configure the model to respond with audio.
        new LiveGenerationConfig.Builder()
                .setResponseModality(ResponseModality.AUDIO)
                .build()
);
LiveModelFutures liveModel = LiveModelFutures.from(lm);

ListenableFuture<LiveSession> sessionFuture =  liveModel.connect();

Futures.addCallback(sessionFuture, new FutureCallback<LiveSession>() {
    @Override
    public void onSuccess(LiveSession ses) {
	 LiveSessionFutures session = LiveSessionFutures.from(ses);
        session.startAudioConversation();
    }
    @Override
    public void onFailure(Throwable t) {
        // Handle exceptions
    }
}, executor);

Web

Live API를 사용하려면 LiveGenerativeModel 인스턴스를 만들고 응답 모드AUDIO로 설정합니다.


import { initializeApp } from "firebase/app";
import { getAI, getLiveGenerativeModel, GoogleAIBackend, ResponseModality } 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 `LiveGenerativeModel` instance with a model that supports the Live API.
const liveModel = getLiveGenerativeModel(ai, {
  model: "gemini-2.5-flash-native-audio-preview-12-2025",
  // Configure the model to respond with audio.
  generationConfig: {
    responseModalities: [ResponseModality.AUDIO],
  },
});

const session = await liveModel.connect();

// Start the audio conversation.
const audioConversationController = await startAudioConversation(session);

// ... Later, to stop the audio conversation
// await audioConversationController.stop()

Dart

Live API를 사용하려면 LiveGenerativeModel 인스턴스를 만들고 응답 모드audio로 설정합니다.


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

late LiveModelSession _session;
final _audioRecorder = YourAudioRecorder();

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

// Initialize the Gemini Developer API backend service.
// Create a `liveGenerativeModel` instance with a model that supports the Live API.
final liveModel = FirebaseAI.googleAI().liveGenerativeModel(
  model: 'gemini-2.5-flash-native-audio-preview-12-2025',
  // Configure the model to respond with audio.
  liveGenerationConfig: LiveGenerationConfig(
    responseModalities: [ResponseModalities.audio],
  ),
);

_session = await liveModel.connect();

final audioRecordStream = _audioRecorder.startRecordingStream();
// Map the Uint8List stream to InlineDataPart stream.
final mediaChunkStream = audioRecordStream.map((data) {
  return InlineDataPart('audio/pcm', data);
});
await _session.startMediaStream(mediaChunkStream);

// In a separate thread, receive the audio response from the model.
await for (final message in _session.receive()) {
   // Process the received message.
}

Unity

Live API를 사용하려면 LiveModel 인스턴스를 만들고 응답 모드Audio로 설정합니다.


using Firebase;
using Firebase.AI;

async Task SendTextReceiveAudio() {
  // Initialize the Gemini Developer API backend service.
  // Create a `LiveModel` instance with a model that supports the Live API.
  var liveModel = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).GetLiveModel(
      modelName: "gemini-2.5-flash-native-audio-preview-12-2025",
      // Configure the model to respond with audio.
      liveGenerationConfig: new LiveGenerationConfig(
          responseModalities: new[] { ResponseModality.Audio })
    );

  LiveSession session = await liveModel.ConnectAsync();

  // Start a coroutine to send audio from the Microphone.
  var recordingCoroutine = StartCoroutine(SendAudio(session));

  // Start receiving the response.
  await ReceiveAudio(session);
}

IEnumerator SendAudio(LiveSession liveSession) {
  string microphoneDeviceName = null;
  int recordingFrequency = 16000;
  int recordingBufferSeconds = 2;

  var recordingClip = Microphone.Start(microphoneDeviceName, true,
                                       recordingBufferSeconds, recordingFrequency);

  int lastSamplePosition = 0;
  while (true) {
    if (!Microphone.IsRecording(microphoneDeviceName)) {
      yield break;
    }

    int currentSamplePosition = Microphone.GetPosition(microphoneDeviceName);

    if (currentSamplePosition != lastSamplePosition) {
      // The Microphone uses a circular buffer, so we need to check if the
      // current position wrapped around to the beginning, and handle it accordingly.
      int sampleCount;
      if (currentSamplePosition > lastSamplePosition) {
        sampleCount = currentSamplePosition - lastSamplePosition;
      } else {
        sampleCount = recordingClip.samples - lastSamplePosition + currentSamplePosition;
      }

      if (sampleCount > 0) {
        // Get the audio chunk.
        float[] samples = new float[sampleCount];
        recordingClip.GetData(samples, lastSamplePosition);

        // Send the data, discarding the resulting Task to avoid the warning.
        _ = liveSession.SendAudioAsync(samples);

        lastSamplePosition = currentSamplePosition;
      }
    }

    // Wait for a short delay before reading the next sample from the Microphone.
    const float MicrophoneReadDelay = 0.5f;
    yield return new WaitForSeconds(MicrophoneReadDelay);
  }
}

Queue audioBuffer = new();

async Task ReceiveAudio(LiveSession liveSession) {
  int sampleRate = 24000;
  int channelCount = 1;

  // Create a looping AudioClip to fill with the received audio data.
  int bufferSamples = (int)(sampleRate * channelCount);
  AudioClip clip = AudioClip.Create("StreamingPCM", bufferSamples, channelCount,
                                    sampleRate, true, OnAudioRead);

  // Attach the clip to an AudioSource and start playing it.
  AudioSource audioSource = GetComponent();
  audioSource.clip = clip;
  audioSource.loop = true;
  audioSource.Play();

  // Start receiving the response.
  await foreach (var message in liveSession.ReceiveAsync()) {
    // Process the received message
    foreach (float[] pcmData in message.AudioAsFloat) {
      lock (audioBuffer) {
        foreach (float sample in pcmData) {
          audioBuffer.Enqueue(sample);
        }
      }
    }
  }
}

// This method is called by the AudioClip to load audio data.
private void OnAudioRead(float[] data) {
  int samplesToProvide = data.Length;
  int samplesProvided = 0;

  lock(audioBuffer) {
    while (samplesProvided < samplesToProvide && audioBuffer.Count > 0) {
      data[samplesProvided] = audioBuffer.Dequeue();
      samplesProvided++;
    }
  }

  while (samplesProvided < samplesToProvide) {
    data[samplesProvided] = 0.0f;
    samplesProvided++;
  }
}



가격 책정 및 토큰 수 계산

선택한 Gemini API 제공업체의 문서(Gemini Developer API | Agent Platform Gemini API (formerly Vertex AI))에서 Live API 모델의 가격 책정 정보를 확인할 수 있습니다.

Gemini API 제공업체와 관계없이 Live API는 토큰 수 계산 API를 지원하지 않습니다.



또 뭘 할 수 있니?