شما میتوانید از یک مدل Gemini بخواهید فایلهای صوتی که شما ارائه میدهید را چه به صورت درونخطی (با کدگذاری base64) و چه از طریق URL تجزیه و تحلیل کند. وقتی از Firebase AI Logic استفاده میکنید، میتوانید این درخواست را مستقیماً از برنامه خود انجام دهید.
با این قابلیت، میتوانید کارهایی مانند موارد زیر را انجام دهید:
- توصیف، خلاصه کردن یا پاسخ به سوالات مربوط به محتوای صوتی
- رونویسی محتوای صوتی
- بخشهای خاصی از صدا را با استفاده از مهرهای زمانی تجزیه و تحلیل کنید
پرش به نمونههای کد پرش به کد برای پاسخهای استریمشده
| برای گزینههای بیشتر برای کار با صدا، به راهنماهای دیگر مراجعه کنید. تولید خروجی ساختاریافته ، چت چند نوبتی ، استریمینگ دوطرفه | 
| برای مشاهده محتوا و کد مخصوص ارائهدهنده در این صفحه، روی ارائهدهنده API Gemini خود کلیک کنید. | 
 اگر هنوز این کار را نکردهاید، راهنمای شروع به کار را تکمیل کنید، که نحوه راهاندازی پروژه Firebase، اتصال برنامه به Firebase، افزودن SDK، راهاندازی سرویس backend برای ارائهدهنده API انتخابی Gemini و ایجاد یک نمونه GenerativeModel را شرح میدهد.
شما میتوانید از این فایل عمومی با نوع MIME
audio/mp3( مشاهده یا دانلود فایل ) استفاده کنید.https://storage.googleapis.com/cloud-samples-data/generative-ai/audio/pixel.mp3
| قبل از امتحان کردن این نمونه، بخش «قبل از شروع» این راهنما را برای راهاندازی پروژه و برنامه خود تکمیل کنید. در آن بخش، شما همچنین میتوانید روی دکمهای برای ارائهدهندهی API Gemini انتخابی خود کلیک کنید تا محتوای خاص ارائهدهنده را در این صفحه مشاهده کنید . | 
 شما میتوانید از یک مدل Gemini بخواهید با ارائه متن و صدا، متن تولید کند - و mimeType فایل ورودی و خود فایل را ارائه دهد. الزامات و توصیههایی برای فایلهای ورودی را بعداً در این صفحه بیابید.
 شما میتوانید 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-2.5-flash")
// Provide the audio as `Data`
guard let audioData = try? Data(contentsOf: audioURL) else {
    print("Error loading audio data.")
    return // Or handle the error appropriately
}
// Specify the appropriate audio MIME type
let audio = InlineDataPart(data: audioData, mimeType: "audio/mpeg")
// Provide a text prompt to include with the audio
let prompt = "Transcribe what's said in this audio recording."
// To generate text output, call `generateContent` with the audio and text prompt
let response = try await model.generateContent(audio, prompt)
// Print the generated text, handling the case where it might be nil
print(response.text ?? "No text in response.")
 شما میتوانید generateContent() برای تولید متن از ورودی چندوجهی متن و یک فایل صوتی واحد فراخوانی کنید.
// 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-2.5-flash")
val contentResolver = applicationContext.contentResolver
val inputStream = contentResolver.openInputStream(audioUri)
if (inputStream != null) {  // Check if the audio loaded successfully
    inputStream.use { stream ->
        val bytes = stream.readBytes()
        // Provide a prompt that includes the audio specified above and text
        val prompt = content {
            inlineData(bytes, "audio/mpeg")  // Specify the appropriate audio MIME type
            text("Transcribe what's said in this audio recording.")
        }
        // To generate text output, call `generateContent` with the prompt
        val response = model.generateContent(prompt)
        // Log the generated text, handling the case where it might be null
        Log.d(TAG, response.text?: "")
    }
} else {
    Log.e(TAG, "Error getting input stream for audio.")
    // Handle the error appropriately
}
 شما میتوانید generateContent() برای تولید متن از ورودی چندوجهی متن و یک فایل صوتی واحد فراخوانی کنید.
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-2.5-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(audioUri)) {
    File audioFile = new File(new URI(audioUri.toString()));
    int audioSize = (int) audioFile.length();
    byte audioBytes = new byte[audioSize];
    if (stream != null) {
        stream.read(audioBytes, 0, audioBytes.length);
        stream.close();
        // Provide a prompt that includes the audio specified above and text
        Content prompt = new Content.Builder()
              .addInlineData(audioBytes, "audio/mpeg")  // Specify the appropriate audio MIME type
              .addText("Transcribe what's said in this audio recording.")
              .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 text = result.getText();
                Log.d(TAG, (text == null) ? "" : text);
            }
            @Override
            public void onFailure(Throwable t) {
                Log.e(TAG, "Failed to generate a response", t);
            }
        }, executor);
    } else {
        Log.e(TAG, "Error getting input stream for file.");
        // Handle the error appropriately
    }
} catch (IOException e) {
    Log.e(TAG, "Failed to read the audio file", e);
} catch (URISyntaxException e) {
    Log.e(TAG, "Invalid audio file", e);
}
 شما میتوانید 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-2.5-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(','));
    reader.readAsDataURL(file);
  });
  return {
    inlineData: { data: await base64EncodedDataPromise, mimeType: file.type },
  };
}
async function run() {
  // Provide a text prompt to include with the audio
  const prompt = "Transcribe what's said in this audio recording.";
  // Prepare audio for input
  const fileInputEl = document.querySelector("input[type=file]");
  const audioPart = await fileToGenerativePart(fileInputEl.files);
  // To generate text output, call `generateContent` with the text and audio
  const result = await model.generateContent([prompt, audioPart]);
  // Log the generated text, handling the case where it might be undefined
  console.log(result.response.text() ?? "No text in response.");
}
run();
 شما میتوانید 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-2.5-flash');
// Provide a text prompt to include with the audio
final prompt = TextPart("Transcribe what's said in this audio recording.");
// Prepare audio for input
final audio = await File('audio0.mp3').readAsBytes();
// Provide the audio as `Data` with the appropriate audio MIME type
final audioPart = InlineDataPart('audio/mpeg', audio);
// To generate text output, call `generateContent` with the text and audio
final response = await model.generateContent([
  Content.multi([prompt,audioPart])
]);
// Print the generated text
print(response.text);
 شما میتوانید تابع 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-2.5-flash");
// Provide a text prompt to include with the audio
var prompt = ModelContent.Text("Transcribe what's said in this audio recording.");
// Provide the audio as `data` with the appropriate audio MIME type
var audio = ModelContent.InlineData("audio/mpeg",
      System.IO.File.ReadAllBytes(System.IO.Path.Combine(
        UnityEngine.Application.streamingAssetsPath, "audio0.mp3")));
// To generate text output, call `GenerateContentAsync` with the text and audio
var response = await model.GenerateContentAsync(new [] { prompt, audio });
// Print the generated text
UnityEngine.Debug.Log(response.Text ?? "No text in response.");
یاد بگیرید که چگونه یک مدل را انتخاب کنیدمناسب برای مورد استفاده و برنامه شما.
| قبل از امتحان کردن این نمونه، بخش «قبل از شروع» این راهنما را برای راهاندازی پروژه و برنامه خود تکمیل کنید. در آن بخش، شما همچنین میتوانید روی دکمهای برای ارائهدهندهی API Gemini انتخابی خود کلیک کنید تا محتوای خاص ارائهدهنده را در این صفحه مشاهده کنید . | 
 شما میتوانید با منتظر نماندن برای کل نتیجه از تولید مدل، و در عوض استفاده از استریمینگ برای مدیریت نتایج جزئی، به تعاملات سریعتری دست یابید. برای استریمینگ پاسخ، generateContentStream فراخوانی کنید. 
 میتوانید تابع generateContentStream() را برای پخش متن تولید شده از ورودی چندوجهی متن و یک فایل صوتی واحد فراخوانی کنید.
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-2.5-flash")
// Provide the audio as `Data`
guard let audioData = try? Data(contentsOf: audioURL) else {
    print("Error loading audio data.")
    return // Or handle the error appropriately
}
// Specify the appropriate audio MIME type
let audio = InlineDataPart(data: audioData, mimeType: "audio/mpeg")
// Provide a text prompt to include with the audio
let prompt = "Transcribe what's said in this audio recording."
// To stream generated text output, call `generateContentStream` with the audio and text prompt
let contentStream = try model.generateContentStream(audio, prompt)
// Print the generated text, handling the case where it might be nil
for try await chunk in contentStream {
    if let text = chunk.text {
        print(text)
    }
}
 میتوانید تابع generateContentStream() را برای پخش متن تولید شده از ورودی چندوجهی متن و یک فایل صوتی واحد فراخوانی کنید.
// 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-2.5-flash")
val contentResolver = applicationContext.contentResolver
val inputStream = contentResolver.openInputStream(audioUri)
if (inputStream != null) {  // Check if the audio loaded successfully
    inputStream.use { stream ->
        val bytes = stream.readBytes()
        // Provide a prompt that includes the audio specified above and text
        val prompt = content {
            inlineData(bytes, "audio/mpeg")  // Specify the appropriate audio MIME type
            text("Transcribe what's said in this audio recording.")
        }
        // To stream generated text output, call `generateContentStream` with the prompt
        var fullResponse = ""
        model.generateContentStream(prompt).collect { chunk ->
            // Log the generated text, handling the case where it might be null
            Log.d(TAG, chunk.text?: "")
            fullResponse += chunk.text?: ""
        }
    }
} else {
    Log.e(TAG, "Error getting input stream for audio.")
    // Handle the error appropriately
}
 میتوانید تابع generateContentStream() را برای پخش متن تولید شده از ورودی چندوجهی متن و یک فایل صوتی واحد فراخوانی کنید.
Publisher از کتابخانه Reactive Streams برمیگردانند. 
// 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-2.5-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(audioUri)) {
    File audioFile = new File(new URI(audioUri.toString()));
    int audioSize = (int) audioFile.length();
    byte audioBytes = new byte[audioSize];
    if (stream != null) {
        stream.read(audioBytes, 0, audioBytes.length);
        stream.close();
        // Provide a prompt that includes the audio specified above and text
        Content prompt = new Content.Builder()
              .addInlineData(audioBytes, "audio/mpeg")  // Specify the appropriate audio MIME type
              .addText("Transcribe what's said in this audio recording.")
              .build();
        // To stream generated text output, call `generateContentStream` with the prompt
        Publisher<GenerateContentResponse> streamingResponse =
                model.generateContentStream(prompt);
        StringBuilder fullResponse = new StringBuilder();
        streamingResponse.subscribe(new Subscriber<GenerateContentResponse>() {
            @Override
            public void onNext(GenerateContentResponse generateContentResponse) {
                String chunk = generateContentResponse.getText();
                String text = (chunk == null) ? "" : chunk;
                Log.d(TAG, text);
                fullResponse.append(text);
            }
            @Override
            public void onComplete() {
                Log.d(TAG, fullResponse.toString());
            }
            @Override
            public void onError(Throwable t) {
                Log.e(TAG, "Failed to generate a response", t);
            }
            @Override
            public void onSubscribe(Subscription s) {
            }
         });
    } else {
        Log.e(TAG, "Error getting input stream for file.");
        // Handle the error appropriately
    }
} catch (IOException e) {
    Log.e(TAG, "Failed to read the audio file", e);
} catch (URISyntaxException e) {
    Log.e(TAG, "Invalid audio file", e);
}
 میتوانید تابع generateContentStream() را برای پخش متن تولید شده از ورودی چندوجهی متن و یک فایل صوتی واحد فراخوانی کنید. 
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-2.5-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(','));
    reader.readAsDataURL(file);
  });
  return {
    inlineData: { data: await base64EncodedDataPromise, mimeType: file.type },
  };
}
async function run() {
  // Provide a text prompt to include with the audio
  const prompt = "Transcribe what's said in this audio recording.";
  // Prepare audio for input
  const fileInputEl = document.querySelector("input[type=file]");
  const audioPart = await fileToGenerativePart(fileInputEl.files);
  // To stream generated text output, call `generateContentStream` with the text and audio
  const result = await model.generateContentStream([prompt, audioPart]);
  // Log the generated text
  for await (const chunk of result.stream) {
    const chunkText = chunk.text();
    console.log(chunkText);
  }
}
run();
 میتوانید تابع generateContentStream() را برای پخش متن تولید شده از ورودی چندوجهی متن و یک فایل صوتی واحد فراخوانی کنید. 
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-2.5-flash');
// Provide a text prompt to include with the audio
final prompt = TextPart("Transcribe what's said in this audio recording.");
// Prepare audio for input
final audio = await File('audio0.mp3').readAsBytes();
// Provide the audio as `Data` with the appropriate audio MIME type
final audioPart = InlineDataPart('audio/mpeg', audio);
// To stream generated text output, call `generateContentStream` with the text and audio
final response = await model.generateContentStream([
  Content.multi([prompt, audioPart])
]);
// Print the generated text
await for (final chunk in response) {
  print(chunk.text);
}
 میتوانید تابع GenerateContentStreamAsync() را برای استریم متن تولید شده از ورودی چندوجهی متن و یک فایل صوتی واحد فراخوانی کنید. 
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-2.5-flash");
// Provide a text prompt to include with the audio
var prompt = ModelContent.Text("Transcribe what's said in this audio recording.");
// Provide the audio as `data` with the appropriate audio MIME type
var audio = ModelContent.InlineData("audio/mpeg",
      System.IO.File.ReadAllBytes(System.IO.Path.Combine(
        UnityEngine.Application.streamingAssetsPath, "audio0.mp3")));
// To stream generated text output, call `GenerateContentStreamAsync` with the text and audio
var responseStream = model.GenerateContentStreamAsync(new [] { prompt, audio });
// Print the generated text
await foreach (var response in responseStream) {
  if (!string.IsNullOrWhiteSpace(response.Text)) {
    UnityEngine.Debug.Log(response.Text);
  }
}
یاد بگیرید که چگونه یک مدل را انتخاب کنیدمناسب برای مورد استفاده و برنامه شما.
توجه داشته باشید که فایلی که به عنوان داده درونخطی ارائه میشود، در حین انتقال به base64 کدگذاری میشود که باعث افزایش اندازه درخواست میشود. اگر درخواست خیلی بزرگ باشد، خطای HTTP 413 دریافت خواهید کرد.
برای کسب اطلاعات دقیق در مورد موارد زیر، به صفحه «فایلهای ورودی پشتیبانیشده و الزامات» مراجعه کنید:
- گزینههای مختلف برای ارائه یک فایل در یک درخواست (چه به صورت درونخطی و چه با استفاده از URL یا URI فایل)
- الزامات و بهترین شیوهها برای فایلهای صوتی
مدلهای چندوجهی Gemini از انواع MIME صوتی زیر پشتیبانی میکنند:
-  AAC - audio/aac
-  FLAC - audio/flac
-  MP3 - audio/mp3
-  MPA - audio/m4a
-  MPEG - audio/mpeg
-  MPGA - audio/mpga
-  MP4 - audio/mp4
-  اُپوس - audio/opus
-  PCM - audio/pcm
-  WAV - audio/wav
-  وبام - audio/webm
- یاد بگیرید که چگونه قبل از ارسال دستورات طولانی به مدل، توکنها را بشمارید .
- Cloud Storage for Firebase تنظیم کنید تا بتوانید فایلهای بزرگ را در درخواستهای چندوجهی خود بگنجانید و یک راهحل مدیریتشدهتر برای ارائه فایلها در اعلانها داشته باشید. فایلها میتوانند شامل تصاویر، فایلهای PDF، ویدیو و صدا باشند.
-  شروع به فکر کردن در مورد آمادهسازی برای تولید کنید (به چک لیست تولید مراجعه کنید)، از جمله:- راهاندازی Firebase App Check برای محافظت از API Gemini در برابر سوءاستفاده توسط کلاینتهای غیرمجاز.
- ادغام Firebase Remote Config برای بهروزرسانی مقادیر در برنامه شما (مانند نام مدل) بدون انتشار نسخه جدید برنامه.
 
- مکالمات چند نوبتی (چت) بسازید.
- تولید متن از درخواستهای فقط متنی .
- خروجی ساختاریافته (مانند JSON) را از هر دو حالت متنی و چندوجهی تولید کنید.
- تصاویر را از متنهای پیشنهادی ( Gemini یا Imagen ) تولید کنید.
- ورودی و خروجی (از جمله صدا) را با استفاده از Gemini Live API استریم کنید.
- از ابزارهایی (مانند فراخوانی تابع و اتصال به زمین با جستجوی گوگل ) برای اتصال یک مدل Gemini به سایر بخشهای برنامه و سیستمها و اطلاعات خارجی خود استفاده کنید.
شما همچنین میتوانید با استفاده از دستورات و پیکربندیهای مدل، آزمایش کنید و حتی یک قطعه کد تولید شده با استفاده از Google AI Studio دریافت کنید.
درباره تجربه خود با Firebase AI Logic بازخورد دهید