你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
注释
此功能目前处于公开预览状态。 此预览版在没有服务级别协议的情况下提供,不建议用于生产工作负荷。 某些功能可能不受支持或者受限。 有关详细信息,请参阅 Microsoft Azure 预览版补充使用条款。
LLM 语音由大型语言模型增强的语音模型提供支持,该模型提供改进的质量、深度上下文理解、多语言支持和提示优化功能。 它使用 GPU 加速进行超快速推理,使其非常适合各种方案,包括从音频文件生成字幕和字幕、汇总会议笔记、协助呼叫中心代理、转录语音邮件等。
LLM 语音 API 目前支持以下语音任务:
transcribetranslate
先决条件
推出了 LLM 语音 API 的某个区域中 Foundry Tools 中的 Azure AI 语音资源。 有关受支持区域的当前列表,请参阅 语音服务区域。
音频文件(长度小于 2 小时且大小小于 300 MB),采用批处理听录 API 支持的格式和编解码器之一:WAV、MP3、OPUS/OGG、FLAC、WMA、AAC、WAV 容器中的 ALAW、WAV 容器中的 MULAW、AMR、WebM 和 SPEEX。 有关受支持的音频格式的详细信息,请参阅受支持的音频格式。
使用 LLM 语音 API
支持的语言
目前支持以下语言用于 transcribe 和 translate 任务:
-
English、、Chinese、GermanFrench、Italian、Japanese、Spanish、、Portuguese和Korean。
上传音频
可以通过以下方式提供音频数据:
- 传递内联音频数据。
--form 'audio=@"YourAudioFile"'
- 从公共
audioUrl文件上传音频文件。
--form 'definition": "{\"audioUrl\": \"https://crbn.us/hello.wav"}"'
在以下部分中,内联音频上传用作示例。
调用 LLM 语音 API
使用音频文件和请求正文属性向transcriptions终结点发出多部分/表单数据 POST 请求。
以下示例演示了如何使用指定的区域设置转录音频文件。 如果知道音频文件的地域设置,可以指定它以提高转录准确性并减少延迟。
- 将
YourSpeechResoureKey替换为语音资源密钥。 - 将
YourServiceRegion替换为你的语音资源所在区域。 - 将
YourAudioFile替换为音频文件的路径。
重要
对于建议使用 Microsoft Entra ID 的无密钥身份验证,请将 --header 'Ocp-Apim-Subscription-Key: YourSpeechResoureKey' 替换为 --header "Authorization: Bearer YourAccessToken"。 有关无密钥身份验证的详细信息,请参阅 基于角色的访问控制 作指南。
使用 LLM 语音转录音频
可以使用输入语言转录音频,而无需指定地区代码。 模型根据音频内容自动检测并选择适当的语言。
curl --location 'https://<YourServiceRegion>.api.cognitive.microsoft.com/speechtotext/transcriptions:transcribe?api-version=2025-10-15' \
--header 'Content-Type: multipart/form-data' \
--header 'Ocp-Apim-Subscription-Key: <YourSpeechResourceKey>' \
--form 'audio=@"YourAudioFile.wav"' \
--form 'definition={
"enhancedMode": {
"enabled": true,
"task": "transcribe"
}
}'
使用 LLM 语音翻译音频文件
可以将音频翻译为指定的目标语言。 若要启用翻译,必须在请求中提供目标语言代码。
curl --location 'https://<YourServiceRegion>.api.cognitive.microsoft.com/speechtotext/transcriptions:transcribe?api-version=2025-10-15' \
--header 'Content-Type: multipart/form-data' \
--header 'Ocp-Apim-Subscription-Key: <YourSpeechResourceKey>' \
--form 'audio=@"YourAudioFile.wav"' \
--form 'definition={
"enhancedMode": {
"enabled": true,
"task": "translate",
"targetLanguage": "ko"
}
}'
使用提示优化改变表现
可以提供可选文本以指导 transcribe 或 translate 任务的输出样式。
curl --location 'https://<YourServiceRegion>.api.cognitive.microsoft.com/speechtotext/transcriptions:transcribe?api-version=2025-10-15' \
--header 'Content-Type: multipart/form-data' \
--header 'Ocp-Apim-Subscription-Key: <YourSpeechResourceKey>' \
--form 'audio=@"YourAudioFile.wav"' \
--form 'definition={
"enhancedMode": {
"enabled": true,
"task": "transcribe",
"prompt": ["Output must be in lexical format."]
}
}'
以下是提示的最佳实践:
- 提示的最大长度为 4,096 个字符。
- 提示最好用英语编写。
- 提示可以指导输出格式设置。 默认情况下,响应使用优化以提高可读性的显示格式。 若要强制实施词法格式,请包括:
Output must be in lexical format. - 提示可以放大特定短语或首字母缩略词的突出性,从而提高识别可能性。 使用:
Pay attention to *phrase1*, *phrase2*, …. 为获得最佳结果,请限制每个提示的短语数。 - 通常忽略与语音任务(例如)
Tell me a story.无关的提示。
更多配置选项
可以将其他配置选项与 快速听录 相结合,以启用增强功能,例如 diarization, profanityFilterMode和 channels。
curl --location 'https://<YourServiceRegion>.api.cognitive.microsoft.com/speechtotext/transcriptions:transcribe?api-version=2025-10-15' \
--header 'Content-Type: multipart/form-data' \
--header 'Ocp-Apim-Subscription-Key: <YourSpeechResourceKey>' \
--form 'audio=@"YourAudioFile.wav"' \
--form 'definition={
"enhancedMode": {
"enabled": true,
"task": "transcribe",
"prompt": ["Output must be in lexical format."]
},
"diarization": {
"maxSpeakers": 2,
"enabled": true
},
"profanityFilterMode": "Masked"
}'
某些配置选项(例如 locales ,和 phraseLists)不是必需的或不适用于 LLM 语音,并且可以从请求中省略。 从 快速听录的配置选项中了解详细信息。
示例响应
在 JSON 响应中,该 combinedPhrases 属性包含完整的转录或翻译的文本,该 phrases 属性包含段级和字级详细信息。
{
"durationMilliseconds": 57187,
"combinedPhrases": [
{
"text": "With custom speech,you can evaluate and improve the microsoft speech to text accuracy for your applications and products 现成的语音转文本,利用通用语言模型作为一个基本模型,使用microsoft自有数据进行训练,并反映常用的口语。此基础模型使用那些代表各常见领域的方言和发音进行了预先训练。 Quand vous effectuez une demande de reconnaissance vocale, le modèle de base le plus récent pour chaque langue prise en charge est utilisé par défaut. Le modèle de base fonctionne très bien dans la plupart des scénarios de reconnaissance vocale. A custom model can be used to augment the base model to improve recognition of domain specific vocabulary specified to the application by providing text data to train the model. It can also be used to improve recognition based for the specific audio conditions of the application by providing audio data with reference transcriptions."
}
],
"phrases": [
{
"offsetMilliseconds": 80,
"durationMilliseconds": 6960,
"text": "With custom speech,you can evaluate and improve the microsoft speech to text accuracy for your applications and products.",
"words": [
{
"text": "with",
"offsetMilliseconds": 80,
"durationMilliseconds": 160
},
{
"text": "custom",
"offsetMilliseconds": 240,
"durationMilliseconds": 480
},
{
"text": "speech",
"offsetMilliseconds": 720,
"durationMilliseconds": 360
},,
// More transcription results...
// Redacted for brevity
],
"locale": "en-us",
"confidence": 0
},
{
"offsetMilliseconds": 8000,
"durationMilliseconds": 8600,
"text": "现成的语音转文本,利用通用语言模型作为一个基本模型,使用microsoft自有数据进行训练,并反映常用的口语。此基础模型使用那些代表各常见领域的方言和发音进行了预先训练。",
"words": [
{
"text": "现",
"offsetMilliseconds": 8000,
"durationMilliseconds": 40
},
{
"text": "成",
"offsetMilliseconds": 8040,
"durationMilliseconds": 40
},
// More transcription results...
// Redacted for brevity
{
"text": "训",
"offsetMilliseconds": 16400,
"durationMilliseconds": 40
},
{
"text": "练",
"offsetMilliseconds": 16560,
"durationMilliseconds": 40
},
],
"locale": "zh-cn",
"confidence": 0
// More transcription results...
// Redacted for brevity
{
"text": "with",
"offsetMilliseconds": 54720,
"durationMilliseconds": 200
},
{
"text": "reference",
"offsetMilliseconds": 54920,
"durationMilliseconds": 360
},
{
"text": "transcriptions.",
"offsetMilliseconds": 55280,
"durationMilliseconds": 1200
}
],
"locale": "en-us",
"confidence": 0
}
]
}
响应格式与其他现有语音转文本输出(如快速听录和批量听录)保持一致。 关键不同点包括:
-
durationMilliseconds任务不支持词级offsetMilliseconds和translate。 -
translate任务不支持分割,仅返回speaker1标签。 -
confidence不可用,并且始终为0。
先决条件
- 一份 Azure 订阅。 免费创建一个。
- Python 3.9 或更高版本。 如果未安装合适的 Python 版本,则可以按照 VS Code Python 教程中的说明操作,这是在操作系统上安装 Python 的最简单方法。
- 在一个受支持的区域中创建的 Microsoft Foundry 资源 。 有关区域可用性的详细信息,请参阅 区域支持。
- 要转录的示例
.wav音频文件。
Microsoft Entra ID 先决条件
若要使用 Microsoft Entra ID 进行推荐的无密钥身份验证,你需要:
- 安装使用 Microsoft Entra ID 进行无密钥身份验证所需的 Azure CLI。
- 将
Cognitive Services User角色分配给用户帐户。 你可以在 Azure 门户的“访问控制(IAM)”“添加角色分配”下分配角色。>
设置
使用以下命令创建一个名为
llm-speech-quickstart的新文件夹,并转到快速入门文件夹:mkdir llm-speech-quickstart && cd llm-speech-quickstart创建并激活虚拟 Python 环境以安装本教程所需的包。 建议在安装 Python 包时始终使用虚拟或 conda 环境。 否则,可以中断 Python 的全局安装。 如果已安装 Python 3.9 或更高版本,请使用以下命令创建虚拟环境:
py -3 -m venv .venv .venv\Scripts\Activate.ps1激活 Python 环境时,从命令行运行
python或pip会使用应用程序.venv文件夹中的 Python 解释器。deactivate使用命令退出 Python 虚拟环境。 稍后可以根据需要重新激活它。创建名为 requirements.txt的文件。 将以下包添加到文件:
azure-ai-transcription azure-identity安装这些软件包:
pip install -r requirements.txt
设置环境变量。
需要检索资源终结点和 API 密钥进行身份验证。
登录 Foundry 门户(经典版)。
从左侧菜单中选择 管理中心 。
选择左侧Connected resources,找到你的Microsoft Foundry资源(如果不存在,请添加连接)。 然后复制 API 密钥 和 目标 (终结点)值。 使用这些值设置环境变量。
设置以下环境变量:
$env:AZURE_SPEECH_ENDPOINT="<your-speech-endpoint>" $env:AZURE_SPEECH_API_KEY="<your-api-key>"
使用 LLM 语音转录音频
LLM 语音使用 EnhancedModeProperties 类启用大型语言模型增强的转录功能。 模型会自动检测音频中的语言。
使用以下代码创建名为
llm_speech_transcribe.py的文件:import os from dotenv import load_dotenv from azure.core.credentials import AzureKeyCredential from azure.ai.transcription import TranscriptionClient load_dotenv() from azure.ai.transcription.models import ( TranscriptionContent, TranscriptionOptions, EnhancedModeProperties, ) # Get configuration from environment variables endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] # Optional: we recommend using role based access control (RBAC) for production scenarios api_key = os.environ["AZURE_SPEECH_API_KEY"] if api_key: credential = AzureKeyCredential(api_key) else: from azure.identity import DefaultAzureCredential credential = DefaultAzureCredential() # Create the transcription client client = TranscriptionClient(endpoint=endpoint, credential=credential) # Path to your audio file (replace with your own file path) audio_file_path = "<path-to-your-audio-file.wav>" # Open and read the audio file with open(audio_file_path, "rb") as audio_file: # Create enhanced mode properties for LLM speech transcription enhanced_mode = EnhancedModeProperties( task="transcribe", prompt=[], ) # Create transcription options with enhanced mode options = TranscriptionOptions(enhanced_mode=enhanced_mode) # Create the request content request_content = TranscriptionContent(definition=options, audio=audio_file) # Transcribe the audio result = client.transcribe(request_content) # Print the transcription result print(f"Transcription: {result.combined_phrases[0].text}") # Print detailed phrase information if result.phrases: print("\nDetailed phrases:") for phrase in result.phrases: print(f" [{phrase.offset_milliseconds}ms]: {phrase.text}")参考: TranscriptionClient | TranscriptionContent | TranscriptionOptions | EnhancedModeProperties
将
<path-to-your-audio-file.wav>替换为音频文件的路径。 该服务支持 WAV、MP3、FLAC、OGG 和其他常见音频格式。运行 Python 脚本。
python llm_speech_transcribe.py
输出
该脚本将听录结果输出到控制台:
Transcription: Hi there. This is a sample voice recording created for speech synthesis testing. The quick brown fox jumps over the lazy dog. Just a fun way to include every letter of the alphabet. Numbers, like one, two, three, are spoken clearly. Let's see how well this voice captures tone, timing, and natural rhythm. This audio is provided by samplefiles.com.
Detailed phrases:
[40ms]: Hi there.
[800ms]: This is a sample voice recording created for speech synthesis testing.
[5440ms]: The quick brown fox jumps over the lazy dog.
[9040ms]: Just a fun way to include every letter of the alphabet.
[12720ms]: Numbers, like one, two, three, are spoken clearly.
[17200ms]: Let's see how well this voice captures tone, timing, and natural rhythm.
[22480ms]: This audio is provided by samplefiles.com.
使用 LLM 语音翻译音频
还可以使用 LLM 语音将音频翻译成目标语言。 将 task 设置为 translate,并指定 target_language。
使用以下代码创建名为
llm_speech_translate.py的文件:import os from dotenv import load_dotenv from azure.core.credentials import AzureKeyCredential from azure.ai.transcription import TranscriptionClient load_dotenv() from azure.ai.transcription.models import ( TranscriptionContent, TranscriptionOptions, EnhancedModeProperties, ) # Get configuration from environment variables endpoint = os.environ["AZURE_SPEECH_ENDPOINT"] # Optional: we recommend using role based access control (RBAC) for production scenarios api_key = os.environ["AZURE_SPEECH_API_KEY"] if api_key: credential = AzureKeyCredential(api_key) else: from azure.identity import DefaultAzureCredential credential = DefaultAzureCredential() # Create the transcription client client = TranscriptionClient(endpoint=endpoint, credential=credential) # Path to your audio file (replace with your own file path) audio_file_path = "<path-to-your-audio-file.wav>" # Open and read the audio file with open(audio_file_path, "rb") as audio_file: # Create enhanced mode properties for LLM speech translation # Translate to another language enhanced_mode = EnhancedModeProperties( task="translate", target_language="de", prompt=[ "Translate the following audio to German.", "Convert number words to numbers." ], # Optional prompts to guide the enhanced mode ) # Create transcription options with enhanced mode options = TranscriptionOptions(locales=["en-US"], enhanced_mode=enhanced_mode) # Create the request content request_content = TranscriptionContent(definition=options, audio=audio_file) # Translate the audio result = client.transcribe(request_content) # Print the translation result print(f"Translation: {result.combined_phrases[0].text}")将
<path-to-your-audio-file.wav>替换为音频文件的路径。运行 Python 脚本。
python llm_speech_translate.py
使用提示优化
可以提供可选提示来指导脚本或翻译任务的输出样式。 在对象EnhancedModeProperties中替换prompt值。
import os
from dotenv import load_dotenv
from azure.core.credentials import AzureKeyCredential
from azure.ai.transcription import TranscriptionClient
load_dotenv()
from azure.ai.transcription.models import (
TranscriptionContent,
TranscriptionOptions,
EnhancedModeProperties,
)
# Get configuration from environment variables
endpoint = os.environ["AZURE_SPEECH_ENDPOINT"]
# Optional: we recommend using role based access control (RBAC) for production scenarios
api_key = os.environ["AZURE_SPEECH_API_KEY"]
if api_key:
credential = AzureKeyCredential(api_key)
else:
from azure.identity import DefaultAzureCredential
credential = DefaultAzureCredential()
# Create the transcription client
client = TranscriptionClient(endpoint=endpoint, credential=credential)
# Path to your audio file (replace with your own file path)
audio_file_path = "<path-to-your-audio-file.wav>"
# Open and read the audio file
with open(audio_file_path, "rb") as audio_file:
# Create enhanced mode properties for LLM speech transcription
enhanced_mode = EnhancedModeProperties(
task="transcribe",
prompt=[
"Create lexical output only,",
"Convert number words to numbers."
], # Optional prompts to guide the enhanced mode, prompt="Create lexical transcription.")
)
# Create transcription options with enhanced mode
options = TranscriptionOptions(enhanced_mode=enhanced_mode)
# Create the request content
request_content = TranscriptionContent(definition=options, audio=audio_file)
# Print request content for debugging
print("Request Content:", request_content, "\n")
# Transcribe the audio
result = client.transcribe(request_content)
# Print the transcription result
print(f"Transcription: {result.combined_phrases[0].text}")
# Print detailed phrase information
if result.phrases:
print("\nDetailed phrases:")
for phrase in result.phrases:
提示的最佳做法:
- 提示的最大长度为 4,096 个字符。
- 提示最好用英语编写。
- 使用
Output must be in lexical format.来强制实施词法格式,而非默认显示格式。 - 用于
Pay attention to *phrase1*, *phrase2*, …改进对特定短语或首字母缩略词的识别。
输出
该脚本将听录结果输出到控制台:
Transcription: Hello, this is a test of the LLM speech transcription service.
Detailed phrases:
[0ms]: Hello, this is a test
[1500ms]: of the LLM speech transcription service.
先决条件
- 一份 Azure 订阅。 免费创建一个。
- Java 开发工具包 (JDK) 8 或更高版本。
- Apache Maven 用于依赖项管理和生成项目。
- 其中一个受支持区域的 语音资源 。 有关区域可用性的详细信息,请参阅 语音服务支持的区域。
- 要转录的示例
.wav音频文件。
设置环境
创建一个名为
llm-speech-quickstart的新文件夹并导航到它。mkdir llm-speech-quickstart && cd llm-speech-quickstart在项目目录的根目录中,创建一个
pom.xml文件,并使用以下内容:<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>transcription-quickstart</artifactId> <version>1.0.0</version> <packaging>jar</packaging> <name>Speech Transcription Quickstart</name> <description>Quickstart sample for Azure Speech Transcription client library.</description> <url>https://github.com/Azure/azure-sdk-for-java</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>com.azure</groupId> <artifactId>azure-ai-speech-transcription</artifactId> <version>1.0.0-beta.2</version> </dependency> <dependency> <groupId>com.azure</groupId> <artifactId>azure-identity</artifactId> <version>1.18.1</version> </dependency> </dependencies> <build> <sourceDirectory>.</sourceDirectory> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.11.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>3.1.0</version> <configuration> <mainClass>TranscriptionQuickstart</mainClass> </configuration> </plugin> </plugins> </build> </project>注释
该
<sourceDirectory>.</sourceDirectory>配置告知 Maven 在当前目录中查找 Java 源文件,而不是默认src/main/java结构。 此配置更改允许更简单的平面项目结构。安装依赖项:
mvn clean install
设置环境变量。
必须对应用程序进行身份验证才能访问语音服务。 SDK 支持 API 密钥和Microsoft Entra ID 身份验证。 它根据设置的环境变量自动检测要使用的方法。
首先,设置语音资源的终结点。 将 <your-speech-endpoint> 替换为您的实际资源名称:
$env:AZURE_SPEECH_ENDPOINT="<your-speech-endpoint>"
然后,选择以下身份验证方法之一:
选项 1:API 密钥身份验证(建议入门)
设置 API 密钥环境变量:
setx AZURE_SPEECH_API_KEY <your-speech-key>
选项 2:Microsoft Entra ID 身份验证(建议用于生产)
请不要设置 AZURE_SPEECH_API_KEY,而是配置以下凭据源之一:
-
Azure CLI:在开发计算机上运行
az login。 - 托管标识:适用于在 Azure 中运行的应用(应用服务、Azure Functions、VM)。
-
环境变量:设置
AZURE_TENANT_ID、AZURE_CLIENT_ID和AZURE_CLIENT_SECRET。 - Visual Studio Code 或 IntelliJ:通过 IDE 登录。
您还需要将 认知服务用户 角色分配给您的身份:
az role assignment create --assignee <your-identity> \
--role "Cognitive Services User" \
--scope /subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.CognitiveServices/accounts/<speech-resource-name>
注释
在 Windows 上设置环境变量后,重启需要读取它们的任何正在运行的程序,包括控制台窗口。 在 Linux 或 macOS 上,运行 source ~/.bashrc (或等效的 shell 配置文件)以使更改生效。
使用 LLM 语音转录音频
LLM 语音使用 EnhancedModeOptions 类启用大型语言模型增强的转录功能。 创建 EnhancedModeOptions 实例时会自动启用增强模式。 模型会自动检测音频中的语言。
使用以下代码在项目目录中创建一个名为 LlmSpeechQuickstart.java 的文件:
import com.azure.ai.speech.transcription.TranscriptionClient;
import com.azure.ai.speech.transcription.TranscriptionClientBuilder;
import com.azure.ai.speech.transcription.models.AudioFileDetails;
import com.azure.ai.speech.transcription.models.EnhancedModeOptions;
import com.azure.ai.speech.transcription.models.TranscriptionOptions;
import com.azure.ai.speech.transcription.models.TranscriptionResult;
import com.azure.core.credential.KeyCredential;
import com.azure.core.util.BinaryData;
import com.azure.identity.DefaultAzureCredentialBuilder;
import java.nio.file.Files;
import java.nio.file.Paths;
public class LlmSpeechQuickstart {
public static void main(String[] args) {
try {
// Get credentials from environment variables
String endpoint = System.getenv("AZURE_SPEECH_ENDPOINT");
String apiKey = System.getenv("AZURE_SPEECH_API_KEY");
// Create client with API key or Entra ID authentication
TranscriptionClientBuilder builder = new TranscriptionClientBuilder()
.endpoint(endpoint);
TranscriptionClient client;
if (apiKey != null && !apiKey.isEmpty()) {
// Use API key authentication
client = builder.credential(new KeyCredential(apiKey)).buildClient();
} else {
// Use Entra ID authentication
client = builder.credential(new DefaultAzureCredentialBuilder().build()).buildClient();
}
// Load audio file
String audioFilePath = "<path-to-your-audio-file.wav>";
byte[] audioData = Files.readAllBytes(Paths.get(audioFilePath));
// Create audio file details
AudioFileDetails audioFileDetails = new AudioFileDetails(BinaryData.fromBytes(audioData));
// Create enhanced mode options for LLM speech transcription
// Enhanced mode is automatically enabled when you create EnhancedModeOptions
EnhancedModeOptions enhancedModeOptions = new EnhancedModeOptions()
.setTask("transcribe");
// Create transcription options with enhanced mode
TranscriptionOptions options = new TranscriptionOptions(audioFileDetails)
.setEnhancedModeOptions(enhancedModeOptions);
// Transcribe the audio
TranscriptionResult result = client.transcribe(options);
// Print result
System.out.println("Transcription:");
result.getCombinedPhrases().forEach(phrase ->
System.out.println(phrase.getText())
);
// Print detailed phrase information
if (result.getPhrases() != null) {
System.out.println("\nDetailed phrases:");
result.getPhrases().forEach(phrase ->
System.out.println(String.format(" [%dms] (%s): %s",
phrase.getOffset(),
phrase.getLocale(),
phrase.getText()))
);
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
将<path-to-your-audio-file.wav>替换为音频文件的路径。 该服务支持 WAV、MP3、FLAC、OGG 和其他常见音频格式。
运行应用程序
使用 Maven 运行应用程序:
mvn compile exec:java
使用 LLM 语音翻译音频
还可以使用 LLM 语音将音频翻译成目标语言。 修改 EnhancedModeOptions 配置以将任务 translate 设置为并指定目标语言。
使用以下代码创建名为 LlmSpeechTranslate.java 的文件:
import com.azure.ai.speech.transcription.TranscriptionClient;
import com.azure.ai.speech.transcription.TranscriptionClientBuilder;
import com.azure.ai.speech.transcription.models.AudioFileDetails;
import com.azure.ai.speech.transcription.models.EnhancedModeOptions;
import com.azure.ai.speech.transcription.models.TranscriptionOptions;
import com.azure.ai.speech.transcription.models.TranscriptionResult;
import com.azure.core.credential.KeyCredential;
import com.azure.core.util.BinaryData;
import java.nio.file.Files;
import java.nio.file.Paths;
public class LlmSpeechTranslate {
public static void main(String[] args) {
try {
// Get credentials from environment variables
String endpoint = System.getenv("AZURE_SPEECH_ENDPOINT");
String apiKey = System.getenv("AZURE_SPEECH_API_KEY");
// Create client
TranscriptionClient client = new TranscriptionClientBuilder()
.endpoint(endpoint)
.credential(new KeyCredential(apiKey))
.buildClient();
// Load audio file
String audioFilePath = "<path-to-your-audio-file.wav>";
byte[] audioData = Files.readAllBytes(Paths.get(audioFilePath));
// Create audio file details
AudioFileDetails audioFileDetails = new AudioFileDetails(BinaryData.fromBytes(audioData));
// Create enhanced mode options for LLM speech translation
// Translate to Korean (supported languages: en, zh, de, fr, it, ja, es, pt, ko)
EnhancedModeOptions enhancedModeOptions = new EnhancedModeOptions()
.setTask("translate")
.setTargetLanguage("ko");
// Create transcription options with enhanced mode
TranscriptionOptions options = new TranscriptionOptions(audioFileDetails)
.setEnhancedModeOptions(enhancedModeOptions);
// Translate the audio
TranscriptionResult result = client.transcribe(options);
// Print translation result
System.out.println("Translation:");
result.getCombinedPhrases().forEach(phrase ->
System.out.println(phrase.getText())
);
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
将<path-to-your-audio-file.wav>替换为音频文件的路径。
若要运行翻译示例,请更新 pom.xml 主类配置或运行:
mvn exec:java -Dexec.mainClass="LlmSpeechTranslate"
使用提示优化
可以提供可选提示来指导脚本或翻译任务的输出样式。
import java.util.Arrays;
// Create enhanced mode options with prompt-tuning
EnhancedModeOptions enhancedModeOptions = new EnhancedModeOptions()
.setTask("transcribe")
.setPrompts(Arrays.asList("Output must be in lexical format."));
// Create transcription options with enhanced mode
TranscriptionOptions options = new TranscriptionOptions(audioFileDetails)
.setEnhancedModeOptions(enhancedModeOptions);
提示的最佳做法:
- 提示的最大长度为 4,096 个字符。
- 提示最好用英语编写。
- 使用
Output must be in lexical format.来强制实施词法格式,而非默认显示格式。 - 用于
Pay attention to *phrase1*, *phrase2*, …改进对特定短语或首字母缩略词的识别。
清理资源
完成快速入门后,请删除项目文件夹:
rm -rf llm-speech-quickstart
注释
语音服务是一项弹性服务。 如果收到 429 错误代码(请求过多),请按照最佳做法在自动缩放期间缓解限制。