如何实时转录多声道音频

注释

此功能目前处于公开预览状态。 此预览版没有附带服务级别协议,建议不要用于生产工作负载。 某些功能可能不受支持,或者可能具有受限功能。 有关详细信息,请参阅适用于 Azure 预览版的补充使用条款

实时多通道听录处理立体声(双声道)音频文件或流,并返回由通道标记的识别结果。 如果每个通道包含需要分别转录的不同音频源,例如客户支持通话的双方,请使用此功能。 语音服务同时转录最多两个通道,并报告每个识别结果的源通道。

这两个通道之间的大量重叠语音可能会增加结果处理延迟。

参考文档 | Package (PyPi) | GitHub上的更多示例

在本指南中,你将使用适用于 Python 的语音 SDK 转录立体声音频源中的内容,并读取每个通道各自独立的语音转文本结果。

先决条件

  • 版本 1.51.0 或更高版本的用于 Python 的语音 SDK
  • 双声道(立体声)WAV 文件或立体声音频流。 语音服务最多转录两个通道。

创建语音配置并启用多通道处理

创建实例 SpeechConfig 并将属性设置为 Speech_EnableMultiChannelProcessingtrue。 将 YourSpeechEndpointYourSpeechKey 替换为您的语音资源终结点和密钥。

import azure.cognitiveservices.speech as speechsdk

speech_config = speechsdk.SpeechConfig(
    subscription="YourSpeechKey", endpoint="YourSpeechEndpoint")
speech_config.speech_recognition_language = "en-US"

# Enable per-channel transcription of up to two channels.
speech_config.set_property(speechsdk.PropertyId.Speech_EnableMultiChannelProcessing, "true")

Speech_EnableMultiChannelProcessing 属性在语音 SDK 版本 1.51.0 或更高版本中可用。 如果使用早期 SDK,请按名称设置相同的属性以实现向后兼容性:

speech_config.set_property_by_name("SPEECH-EnableMultiChannelProcessing", "true")

支持立体声

多通道转写支持立体声音频文件或立体声音频流。 若要转录文件,请从文件名创建 AudioConfig 实例:

audio_config = speechsdk.audio.AudioConfig(filename="stereo.wav")

对于实时源,请从推送或拉取流创建 AudioConfig 实例。 创建流格式时,将通道计数设置为 2

# Match the format of your stereo source: sample rate, bits per sample, and 2 channels.
stream_format = speechsdk.audio.AudioStreamFormat(samples_per_second=16000, bits_per_sample=16, channels=2)
push_stream = speechsdk.audio.PushAudioInputStream(stream_format=stream_format)
audio_config = speechsdk.audio.AudioConfig(stream=push_stream)

# Write raw PCM audio (without the WAV header) to push_stream as it becomes available,
# and call push_stream.close() when the source ends.

识别并读取各通道结果

创建 SpeechRecognizer 实例并使用连续识别。 每个最终结果都包含属性中的 channel 源通道。 多通道听录仅支持连续识别;不支持单次识别(recognize_once)。

import time

speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config, audio_config=audio_config)

done = False

def recognized_cb(evt):
    if evt.result.reason == speechsdk.ResultReason.RecognizedSpeech:
        print("RECOGNIZED (channel {}): {}".format(evt.result.channel, evt.result.text))

def stop_cb(evt):
    global done
    done = True

speech_recognizer.recognized.connect(recognized_cb)
speech_recognizer.session_stopped.connect(stop_cb)
speech_recognizer.canceled.connect(stop_cb)

speech_recognizer.start_continuous_recognition()
while not done:
    time.sleep(0.5)
speech_recognizer.stop_continuous_recognition()

channel 属性标识产生该结果的、从 0 开始编号的通道,这样您就可以将各通道的转写结果分开保存。

将多通道听录与分割相结合

若要识别每个通道中的说话人,请使用一个 ConversationTranscriber 而不是一个 SpeechRecognizer。 转录器在 transcribed 事件中报告最终结果,并且每个结果都同时包含 channelspeaker_id

import time

conversation_transcriber = speechsdk.transcription.ConversationTranscriber(
    speech_config=speech_config, audio_config=audio_config)

done = False

def transcribed_cb(evt):
    if evt.result.reason == speechsdk.ResultReason.RecognizedSpeech:
        print("TRANSCRIBED (channel {}, speaker {}): {}".format(
            evt.result.channel, evt.result.speaker_id, evt.result.text))

def stop_cb(evt):
    global done
    done = True

conversation_transcriber.transcribed.connect(transcribed_cb)
conversation_transcriber.session_stopped.connect(stop_cb)
conversation_transcriber.canceled.connect(stop_cb)

conversation_transcriber.start_transcribing_async().get()
while not done:
    time.sleep(0.5)
conversation_transcriber.stop_transcribing_async().get()

参考文档 | Package (NuGet) | 更多示例请见GitHub

本指南使用适用于 C# 的语音 SDK 来转录立体声音频源,并为每个通道读取单独的语音转文本结果。

先决条件

  • C# 版语音 SDK 1.51.0 或更高版本。
  • 双声道(立体声)WAV 文件或立体声音频流。 语音服务最多转录两个通道。

创建语音配置并启用多通道处理

创建实例 SpeechConfig 并将属性设置为 Speech_EnableMultiChannelProcessingtrue。 将 YourSpeechEndpointYourSpeechKey 替换为您的语音资源终结点和密钥。

using System;
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;
using Microsoft.CognitiveServices.Speech.Transcription;

var speechConfig = SpeechConfig.FromEndpoint(
    new Uri("YourSpeechEndpoint"), "YourSpeechKey");
speechConfig.SpeechRecognitionLanguage = "en-US";

// Enable per-channel transcription of up to two channels.
speechConfig.SetProperty(PropertyId.Speech_EnableMultiChannelProcessing, "true");

Speech_EnableMultiChannelProcessing 属性在语音 SDK 版本 1.51.0 或更高版本中可用。 如果使用早期 SDK,请按名称设置相同的属性以实现向后兼容性:

speechConfig.SetProperty("SPEECH-EnableMultiChannelProcessing", "true");

支持立体声

多通道转写支持立体声音频文件或立体声音频流。 若要转录文件,请从文件名创建 AudioConfig 实例:

using var audioConfig = AudioConfig.FromWavFileInput("stereo.wav");

对于实时源,请从推送或拉取流创建 AudioConfig 实例。 创建流格式时,将通道计数设置为 2

// Match the format of your stereo source: sample rate, bits per sample, and 2 channels.
var streamFormat = AudioStreamFormat.GetWaveFormatPCM(16000, 16, 2);
var pushStream = AudioInputStream.CreatePushStream(streamFormat);
using var audioConfig = AudioConfig.FromStreamInput(pushStream);

// Write raw PCM audio (without the WAV header) to pushStream as it becomes available,
// and call pushStream.Close() when the source ends.

识别并读取各通道结果

创建 SpeechRecognizer 实例并使用连续识别。 每个最终结果都包含属性中的 Channel 源通道。 多通道听录仅支持连续识别;不支持单次识别(RecognizeOnceAsync)。

using var recognizer = new SpeechRecognizer(speechConfig, audioConfig);
var stopRecognition = new TaskCompletionSource<int>();

recognizer.Recognized += (s, e) =>
{
    if (e.Result.Reason == ResultReason.RecognizedSpeech)
    {
        Console.WriteLine($"RECOGNIZED (channel {e.Result.Channel}): {e.Result.Text}");
    }
};

recognizer.Canceled += (s, e) => stopRecognition.TrySetResult(0);
recognizer.SessionStopped += (s, e) => stopRecognition.TrySetResult(0);

await recognizer.StartContinuousRecognitionAsync();
Task.WaitAny(new[] { stopRecognition.Task });
await recognizer.StopContinuousRecognitionAsync();

Channel 属性用于标识生成该结果的从零开始编号的声道,这样您就可以将各个声道的转写文本分开保存。

将多通道听录与分割相结合

若要识别每个通道中的说话人,请使用一个 ConversationTranscriber 而不是一个 SpeechRecognizer。 转写器在 Transcribed 事件中报告最终结果,并且每个结果都包含通道和说话人 ID。

using var conversationTranscriber = new ConversationTranscriber(speechConfig, audioConfig);
var stopTranscription = new TaskCompletionSource<int>();

conversationTranscriber.Transcribed += (s, e) =>
{
    if (e.Result.Reason == ResultReason.RecognizedSpeech)
    {
        Console.WriteLine($"TRANSCRIBED (channel {e.Result.Channel}, speaker {e.Result.SpeakerId}): {e.Result.Text}");
    }
};

conversationTranscriber.Canceled += (s, e) => stopTranscription.TrySetResult(0);
conversationTranscriber.SessionStopped += (s, e) => stopTranscription.TrySetResult(0);

await conversationTranscriber.StartTranscribingAsync();
Task.WaitAny(new[] { stopTranscription.Task });
await conversationTranscriber.StopTranscribingAsync();

参考文档 | Package (NuGet) | 更多示例请见GitHub

本指南使用适用于 C++ 的语音 SDK 来转录立体声音频源,并为每个通道读取单独的语音转文本结果。

先决条件

  • 适用于 C++ 的语音 SDK 版本 1.51.0 或更高版本。
  • 双声道(立体声)WAV 文件或立体声音频流。 语音服务最多转录两个通道。

创建语音配置并启用多通道处理

创建实例 SpeechConfig 并将属性设置为 Speech_EnableMultiChannelProcessingtrue。 将 YourSpeechEndpointYourSpeechKey 替换为您的语音资源终结点和密钥。

#include <speechapi_cxx.h>

using namespace Microsoft::CognitiveServices::Speech;
using namespace Microsoft::CognitiveServices::Speech::Audio;
using namespace Microsoft::CognitiveServices::Speech::Transcription;

auto speechConfig = SpeechConfig::FromEndpoint(
    "YourSpeechEndpoint", "YourSpeechKey");
speechConfig->SetSpeechRecognitionLanguage("en-US");

// Enable per-channel transcription of up to two channels.
speechConfig->SetProperty(PropertyId::Speech_EnableMultiChannelProcessing, "true");

Speech_EnableMultiChannelProcessing 属性在语音 SDK 版本 1.51.0 或更高版本中可用。 如果使用早期 SDK,请按名称设置相同的属性以实现向后兼容性:

speechConfig->SetProperty("SPEECH-EnableMultiChannelProcessing", "true");

支持立体声

多通道转写支持立体声音频文件或立体声音频流。 若要转录文件,请从文件名创建 AudioConfig 实例:

auto audioConfig = AudioConfig::FromWavFileInput("stereo.wav");

对于实时源,请从推送或拉取流创建 AudioConfig 实例。 创建流格式时,将通道计数设置为 2

// Match the format of your stereo source: sample rate, bits per sample, and 2 channels.
auto streamFormat = AudioStreamFormat::GetWaveFormatPCM(16000, 16, 2);
auto pushStream = AudioInputStream::CreatePushStream(streamFormat);
auto audioConfig = AudioConfig::FromStreamInput(pushStream);

// Write raw PCM audio (without the WAV header) to pushStream as it becomes available,
// and call pushStream->Close() when the source ends.

识别并读取各通道结果

创建 SpeechRecognizer 实例并使用连续识别。 每个最终结果包括方法中的 Channel() 源通道。 多通道听录仅支持连续识别;不支持单次识别(RecognizeOnceAsync)。

#include <atomic>
#include <future>

auto recognizer = SpeechRecognizer::FromConfig(speechConfig, audioConfig);
std::promise<void> recognitionEnd;
std::atomic<bool> recognitionEnded{false};

auto signalRecognitionEnd = [&recognitionEnd, &recognitionEnded]()
{
    if (!recognitionEnded.exchange(true))
    {
        recognitionEnd.set_value();
    }
};

recognizer->Recognized.Connect([](const SpeechRecognitionEventArgs& e)
{
    if (e.Result->Reason == ResultReason::RecognizedSpeech)
    {
        printf("RECOGNIZED (channel %d): %s\n", e.Result->Channel(), e.Result->Text.c_str());
    }
});

recognizer->Canceled.Connect([&signalRecognitionEnd](const SpeechRecognitionCanceledEventArgs& e)
{
    if (e.Reason == CancellationReason::Error)
    {
        signalRecognitionEnd();
    }
});

recognizer->SessionStopped.Connect([&signalRecognitionEnd](const SessionEventArgs& e)
{
    signalRecognitionEnd();
});

recognizer->StartContinuousRecognitionAsync().get();
recognitionEnd.get_future().get();
recognizer->StopContinuousRecognitionAsync().get();

该方法 Channel() 返回生成结果的从零开始的通道,以便可以保持每个通道的脚本分开。

将多通道听录与分割相结合

若要识别每个通道中的说话人,请使用一个 ConversationTranscriber 而不是一个 SpeechRecognizer。 转写器在 Transcribed 事件中报告最终结果,并且每个结果都包含通道和说话人 ID。

auto conversationTranscriber = ConversationTranscriber::FromConfig(speechConfig, audioConfig);
std::promise<void> transcriptionEnd;
std::atomic<bool> transcriptionEnded{false};

auto signalTranscriptionEnd = [&transcriptionEnd, &transcriptionEnded]()
{
    if (!transcriptionEnded.exchange(true))
    {
        transcriptionEnd.set_value();
    }
};

conversationTranscriber->Transcribed.Connect([](const ConversationTranscriptionEventArgs& e)
{
    if (e.Result->Reason == ResultReason::RecognizedSpeech)
    {
        printf("TRANSCRIBED (channel %d, speaker %s): %s\n",
            e.Result->Channel(), e.Result->SpeakerId.c_str(), e.Result->Text.c_str());
    }
});

conversationTranscriber->Canceled.Connect([&signalTranscriptionEnd](const ConversationTranscriptionCanceledEventArgs& e)
{
    if (e.Reason == CancellationReason::Error)
    {
        signalTranscriptionEnd();
    }
});

conversationTranscriber->SessionStopped.Connect([&signalTranscriptionEnd](const SessionEventArgs& e)
{
    signalTranscriptionEnd();
});

conversationTranscriber->StartTranscribingAsync().get();
transcriptionEnd.get_future().get();
conversationTranscriber->StopTranscribingAsync().get();

参考文档 | GitHub上的更多示例

在本指南中,你将使用适用于 Java 的语音 SDK 来转录立体声音频源,并分别读取每个通道的语音转文本结果。

先决条件

  • Java 版语音 SDK 1.51.0 或更高版本。
  • 双声道(立体声)WAV 文件或立体声音频流。 语音服务最多转录两个通道。

创建语音配置并启用多通道处理

创建实例 SpeechConfig 并将属性设置为 Speech_EnableMultiChannelProcessingtrue。 将 YourSpeechEndpointYourSpeechKey 替换为您的语音资源终结点和密钥。

import com.microsoft.cognitiveservices.speech.*;
import com.microsoft.cognitiveservices.speech.audio.*;
import com.microsoft.cognitiveservices.speech.transcription.*;
import java.net.URI;

SpeechConfig speechConfig = SpeechConfig.fromEndpoint(
    new URI("YourSpeechEndpoint"), "YourSpeechKey");
speechConfig.setSpeechRecognitionLanguage("en-US");

// Enable per-channel transcription of up to two channels.
speechConfig.setProperty(PropertyId.Speech_EnableMultiChannelProcessing, "true");

Speech_EnableMultiChannelProcessing 属性在语音 SDK 版本 1.51.0 或更高版本中可用。 如果使用早期 SDK,请按名称设置相同的属性以实现向后兼容性:

speechConfig.setProperty("SPEECH-EnableMultiChannelProcessing", "true");

支持立体声

多通道转写支持立体声音频文件或立体声音频流。 若要转录文件,请从文件名创建 AudioConfig 实例:

AudioConfig audioConfig = AudioConfig.fromWavFileInput("stereo.wav");

对于实时源,请从推送或拉取流创建 AudioConfig 实例。 创建流格式时,将通道计数设置为 2

// Match the format of your stereo source: sample rate, bits per sample, and 2 channels.
AudioStreamFormat streamFormat = AudioStreamFormat.getWaveFormatPCM(16000, (short)16, (short)2);
PushAudioInputStream pushStream = AudioInputStream.createPushStream(streamFormat);
AudioConfig audioConfig = AudioConfig.fromStreamInput(pushStream);

// Write raw PCM audio (without the WAV header) to pushStream as it becomes available,
// and call pushStream.close() when the source ends.

识别并读取各通道结果

创建 SpeechRecognizer 实例并使用连续识别。 每个最终结果包括方法中的 getChannel() 源通道。 多通道听录仅支持连续识别;不支持单次识别(recognizeOnceAsync)。

import java.util.concurrent.Semaphore;

SpeechRecognizer recognizer = new SpeechRecognizer(speechConfig, audioConfig);
Semaphore recognitionEnd = new Semaphore(0);

recognizer.recognized.addEventListener((s, e) -> {
    if (e.getResult().getReason() == ResultReason.RecognizedSpeech) {
        System.out.println("RECOGNIZED (channel " + e.getResult().getChannel() + "): " + e.getResult().getText());
    }
});

recognizer.canceled.addEventListener((s, e) -> {
    if (e.getReason() == CancellationReason.Error) {
        recognitionEnd.release();
    }
});

recognizer.sessionStopped.addEventListener((s, e) -> recognitionEnd.release());

recognizer.startContinuousRecognitionAsync().get();
recognitionEnd.acquire();
recognizer.stopContinuousRecognitionAsync().get();

recognizer.close();

该方法 getChannel() 返回生成结果的从零开始的通道,以便可以保持每个通道的脚本分开。

将多通道听录与分割相结合

若要识别每个通道中的说话人,请使用一个 ConversationTranscriber 而不是一个 SpeechRecognizer。 转写器在 transcribed 事件中报告最终结果,并且每个结果都包含通道和说话人 ID。

ConversationTranscriber conversationTranscriber = new ConversationTranscriber(speechConfig, audioConfig);
Semaphore transcriptionEnd = new Semaphore(0);

conversationTranscriber.transcribed.addEventListener((s, e) -> {
    if (e.getResult().getReason() == ResultReason.RecognizedSpeech) {
        System.out.println("TRANSCRIBED (channel " + e.getResult().getChannel()
            + ", speaker " + e.getResult().getSpeakerId() + "): " + e.getResult().getText());
    }
});

conversationTranscriber.canceled.addEventListener((s, e) -> {
    if (e.getReason() == CancellationReason.Error) {
        transcriptionEnd.release();
    }
});

conversationTranscriber.sessionStopped.addEventListener((s, e) -> transcriptionEnd.release());

conversationTranscriber.startTranscribingAsync().get();
transcriptionEnd.acquire();
conversationTranscriber.stopTranscribingAsync().get();

conversationTranscriber.close();

参考文档 | 包 (npm) | GitHub 上的其他示例 | 库源代码

本指南使用适用于 JavaScript 的语音 SDK 来转录立体声音频源,并为每个通道读取单独的语音转文本结果。

先决条件

创建语音配置并启用多通道处理

创建实例 SpeechConfig 并将属性设置为 Speech_EnableMultiChannelProcessingtrue。 将 YourSpeechEndpointYourSpeechKey 替换为您的语音资源终结点和密钥。

const sdk = require("microsoft-cognitiveservices-speech-sdk");

const speechConfig = sdk.SpeechConfig.fromEndpoint(
    new URL("YourSpeechEndpoint"), "YourSpeechKey");
speechConfig.speechRecognitionLanguage = "en-US";

// Enable per-channel transcription of up to two channels.
speechConfig.setProperty(sdk.PropertyId.Speech_EnableMultiChannelProcessing, "true");

Speech_EnableMultiChannelProcessing 属性在语音 SDK 版本 1.51.0 或更高版本中可用。 如果使用早期 SDK,请按名称设置相同的属性以实现向后兼容性:

speechConfig.setProperty("SPEECH-EnableMultiChannelProcessing", "true");

支持立体声

多通道转写支持立体声音频文件或立体声音频流。 若要转录文件,请从文件创建 AudioConfig 实例:

const fs = require("fs");
const audioConfig = sdk.AudioConfig.fromWavFileInput(fs.readFileSync("stereo.wav"));

对于实时源,请从推送流创建 AudioConfig 实例。 创建流格式时,将通道计数设置为 2

// Match the format of your stereo source: sample rate, bits per sample, and 2 channels.
const streamFormat = sdk.AudioStreamFormat.getWaveFormatPCM(16000, 16, 2);
const pushStream = sdk.AudioInputStream.createPushStream(streamFormat);
const audioConfig = sdk.AudioConfig.fromStreamInput(pushStream);

// Write raw PCM audio (without the WAV header) to pushStream as it becomes available,
// and call pushStream.close() when the source ends.

识别并读取各通道结果

创建 SpeechRecognizer 实例并使用连续识别。 多通道听录仅支持连续识别;不支持单次识别(recognizeOnceAsync)。

const recognizer = new sdk.SpeechRecognizer(speechConfig, audioConfig);

recognizer.recognized = (s, e) => {
    if (e.result.reason === sdk.ResultReason.RecognizedSpeech) {
        // e.result.channel identifies the source channel (0 or 1).
        console.log(`RECOGNIZED (channel ${e.result.channel}): ${e.result.text}`);
    }
};

recognizer.sessionStopped = (s, e) => {
    recognizer.stopContinuousRecognitionAsync();
};

recognizer.startContinuousRecognitionAsync();

使用每个结果中的通道值,将各通道的转录文本区分开来。

将多通道听录与分割相结合

若要标识说话人,请使用 ConversationTranscriber 而不是 SpeechRecognizer. 转写器在 transcribed 事件上报告最终结果,并且每个结果都包含一个说话人 ID。

Important

在适用于 JavaScript 的语音 SDK 版本 1.51.0 中, ConversationTranscriber 结果无法可靠地报告源通道。 计划针对版本 1.52.0 进行修复。 如果使用版本 1.51.0,则用于 speakerId 标识说话人,但不用于 channel 按源通道分隔分割结果。 需要可靠的源通道元数据时使用 SpeechRecognizer

const conversationTranscriber = new sdk.ConversationTranscriber(speechConfig, audioConfig);

conversationTranscriber.transcribed = (s, e) => {
    if (e.result.reason === sdk.ResultReason.RecognizedSpeech) {
        console.log(`TRANSCRIBED (speaker ${e.result.speakerId}): ${e.result.text}`);
    }
};

conversationTranscriber.sessionStopped = (s, e) => {
    conversationTranscriber.stopTranscribingAsync();
};

conversationTranscriber.startTranscribingAsync();

参考文档 | Package (Go) | GitHub 上的更多示例

本指南使用语音 SDK for Go 来转录立体声音频源,并为每个通道读取单独的语音转文本结果。

先决条件

  • Go 版语音 SDK 版本 1.52.0 或更高版本。
  • 双声道(立体声)WAV 文件或立体声音频流。 语音服务最多转录两个通道。

注释

在 SDK 1.52.0 发布之前,请直接下载当前的 语音 SDK Go 源

创建语音配置并启用多通道处理

创建 SpeechConfig 实例并启用多通道处理。 将 YourSpeechEndpointYourSpeechKey 替换为您的语音资源终结点和密钥。

import (
    "github.com/Microsoft/cognitive-services-speech-sdk-go/common"
    "github.com/Microsoft/cognitive-services-speech-sdk-go/speech"
)

speechConfig, err := speech.NewSpeechConfigFromEndpointWithSubscription(
    "YourSpeechEndpoint", "YourSpeechKey")
if err != nil {
    fmt.Println("Got an error: ", err)
    return
}
defer speechConfig.Close()
speechConfig.SetSpeechRecognitionLanguage("en-US")

// Enable per-channel transcription of up to two channels.
speechConfig.SetProperty(common.EnableMultiChannelProcessing, "true")

支持立体声

多通道转写支持立体声音频文件或立体声音频流。 若要转录文件,请从文件名创建 AudioConfig 实例:

import "github.com/Microsoft/cognitive-services-speech-sdk-go/audio"

audioConfig, err := audio.NewAudioConfigFromWavFileInput("stereo.wav")
if err != nil {
    fmt.Println("Got an error: ", err)
    return
}
defer audioConfig.Close()

对于实时源,请从格式指定两个通道的流创建 AudioConfig 实例,并在该流可用时将原始 PCM 音频(没有 WAV 标头)写入流。

识别并读取各通道结果

创建 SpeechRecognizer 实例并使用连续识别。 多通道听录仅支持连续识别;不支持单次识别。

每个识别结果都包含一个 Channel 用于标识源音频通道的字段。 通道编号从零开始。

import (
    "github.com/Microsoft/cognitive-services-speech-sdk-go/common"
    "github.com/Microsoft/cognitive-services-speech-sdk-go/speech"
)

speechRecognizer, err := speech.NewSpeechRecognizerFromConfig(speechConfig, audioConfig)
if err != nil {
    fmt.Println("Got an error: ", err)
    return
}
defer speechRecognizer.Close()

speechRecognizer.Recognized(func(event speech.SpeechRecognitionEventArgs) {
    defer event.Close()
    // event.Result.Channel identifies the source channel (0 or 1).
    fmt.Printf("RECOGNIZED (channel %d): %s\n", event.Result.Channel, event.Result.Text)
})

// The Start and Stop methods return a channel that reports the outcome
// of the operation. Read from it to wait for the operation to complete.
if err := <-speechRecognizer.StartContinuousRecognitionAsync(); err != nil {
    fmt.Println("Got an error: ", err)
    return
}
defer func() { <-speechRecognizer.StopContinuousRecognitionAsync() }()

使用每个结果中的通道值,将各通道的转录文本区分开来。

将多通道听录与分割相结合

若要识别每个通道中的说话人,请使用一个 ConversationTranscriber 而不是一个 SpeechRecognizer。 转写器在 Transcribed 事件中报告最终结果,并且每个结果都包含通道和说话人 ID。

import "github.com/Microsoft/cognitive-services-speech-sdk-go/speech"

conversationTranscriber, err := speech.NewConversationTranscriberFromConfig(speechConfig, audioConfig)
if err != nil {
    fmt.Println("Got an error: ", err)
    return
}
defer conversationTranscriber.Close()

conversationTranscriber.Transcribed(func(event speech.ConversationTranscriptionEventArgs) {
    defer event.Close()
    fmt.Printf("TRANSCRIBED (channel %d, speaker %s): %s\n",
        event.Result.Channel, event.Result.SpeakerID, event.Result.Text)
})

if err := <-conversationTranscriber.StartTranscribingAsync(); err != nil {
    fmt.Println("Got an error: ", err)
    return
}
defer func() { <-conversationTranscriber.StopTranscribingAsync() }()

参考文档 | 软件包(下载) | GitHub上的更多示例

在本指南中,你将使用适用于 Objective-C 的语音 SDK 来转写立体声音频源,并为每个声道分别读取单独的语音转文本结果。

先决条件

创建语音配置并启用多通道处理

创建实例 SPXSpeechConfiguration 并将属性设置为 SPXSpeechEnableMultiChannelProcessingtrue. 将 YourSpeechEndpointYourSpeechKey 替换为您的语音资源终结点和密钥。

SPXSpeechConfiguration *speechConfig = [[SPXSpeechConfiguration alloc]
    initWithEndpoint:@"YourSpeechEndpoint" subscription:@"YourSpeechKey"];
speechConfig.speechRecognitionLanguage = @"en-US";

// Enable per-channel transcription of up to two channels.
[speechConfig setPropertyTo:@"true" byId:SPXSpeechEnableMultiChannelProcessing];

SPXSpeechEnableMultiChannelProcessing 属性在语音 SDK 版本 1.51.0 或更高版本中可用。 如果使用早期 SDK,请按名称设置相同的属性以实现向后兼容性:

[speechConfig setPropertyTo:@"true" byName:@"SPEECH-EnableMultiChannelProcessing"];

支持立体声

多通道转写支持立体声音频文件或立体声音频流。 若要转录文件,请从文件名创建 SPXAudioConfiguration 实例:

SPXAudioConfiguration *audioConfig = [[SPXAudioConfiguration alloc] initWithWavFileInput:@"stereo.wav"];

对于实时源,请从格式指定两个通道的流创建 SPXAudioConfiguration 实例,并在该流可用时将原始 PCM 音频(没有 WAV 标头)写入流。

识别并读取各通道结果

创建实例 SPXSpeechRecognizer 并使用连续识别。 多通道听录仅支持连续识别;不支持单次识别(recognizeOnce)。

SPXSpeechRecognizer *recognizer = [[SPXSpeechRecognizer alloc] initWithSpeechConfiguration:speechConfig audioConfiguration:audioConfig];

[recognizer addRecognizedEventHandler:^(SPXSpeechRecognizer *recognizer, SPXSpeechRecognitionEventArgs *evt) {
    SPXSpeechRecognitionResult *result = evt.result;
    if (result != nil && result.reason == SPXResultReason_RecognizedSpeech) {
        // result.channel identifies the source channel (0 or 1).
        NSLog(@"RECOGNIZED (channel %ld): %@", (long)result.channel, result.text);
    }
}];

[recognizer startContinuousRecognition];

使用每个结果中的通道值,将各通道的转录文本分开。

将多通道听录与分割相结合

若要识别每个通道中的扬声器,请使用一个 SPXConversationTranscriber 而不是一个 SPXSpeechRecognizer。 转录器会报告已转录事件的最终结果,并且每条结果都包含通道和说话人 ID。

SPXConversationTranscriber *conversationTranscriber = [[SPXConversationTranscriber alloc] initWithSpeechConfiguration:speechConfig audioConfiguration:audioConfig];

[conversationTranscriber addTranscribedEventHandler:^(SPXConversationTranscriber *transcriber, SPXConversationTranscriptionEventArgs *evt) {
    SPXConversationTranscriptionResult *result = evt.result;
    if (result != nil && result.reason == SPXResultReason_RecognizedSpeech) {
        NSLog(@"TRANSCRIBED (channel %ld, speaker %@): %@", (long)result.channel, result.speakerId, result.text);
    }
}];

[conversationTranscriber startTranscribingAsync:^(BOOL started, NSError *error) {
    if (!started || error != nil) {
        NSLog(@"Could not start transcription: %@", error);
    }
}];

当转录完成后,停止转录器:

[conversationTranscriber stopTranscribingAsync:^(BOOL stopped, NSError *error) {
    if (!stopped || error != nil) {
        NSLog(@"Could not stop transcription: %@", error);
    }
}];

参考文档 | 软件包(下载) | GitHub上的更多示例

本指南使用适用于 Swift 的语音 SDK 来转录立体声音频源,并为每个通道读取单独的语音转文本结果。

先决条件

  • 适用于 Swift 的语音 SDK 版本 1.51.0 或更高版本。
  • 双声道(立体声)WAV 文件或立体声音频流。 语音服务最多转录两个通道。

创建语音配置并启用多通道处理

创建实例 SPXSpeechConfiguration 并启用多通道处理。 将 YourSpeechEndpointYourSpeechKey 替换为您的语音资源终结点和密钥。

let speechConfig = try! SPXSpeechConfiguration(
    endpoint: "YourSpeechEndpoint", subscription: "YourSpeechKey")
speechConfig.speechRecognitionLanguage = "en-US"

// Enable per-channel transcription of up to two channels.
speechConfig.setPropertyTo("true", by: SPXPropertyId.speechEnableMultiChannelProcessing)

多通道属性在语音 SDK 1.51.0 或更高版本中可用。 如果使用早期 SDK,请按名称设置相同的属性以实现向后兼容性:

speechConfig.setPropertyTo("true", byName: "SPEECH-EnableMultiChannelProcessing")

支持立体声

多通道转写支持立体声音频文件或立体声音频流。 若要转录文件,请从文件名创建 SPXAudioConfiguration 实例:

let audioConfig = SPXAudioConfiguration(wavFileInput: "stereo.wav")

对于实时源,请从格式指定两个通道的流创建 SPXAudioConfiguration 实例,并在该流可用时将原始 PCM 音频(没有 WAV 标头)写入流。

识别并读取各通道结果

创建实例 SPXSpeechRecognizer 并使用连续识别。 多通道听录仅支持连续识别;不支持单次识别(recognizeOnce)。

let recognizer = try! SPXSpeechRecognizer(speechConfiguration: speechConfig, audioConfiguration: audioConfig!)

recognizer.addRecognizedEventHandler { recognizer, evt in
    guard let result = evt.result else {
        return
    }

    if result.reason == SPXResultReason.recognizedSpeech {
        // result.channel identifies the source channel (0 or 1).
        print("RECOGNIZED (channel \(result.channel)): \(result.text ?? "")")
    }
}

try! recognizer.startContinuousRecognition()

使用每个结果中的通道值,将各通道的转录文本区分开来。

将多通道听录与分割相结合

若要识别每个通道中的扬声器,请使用一个 SPXConversationTranscriber 而不是一个 SPXSpeechRecognizer。 转写器会报告已转写事件的最终结果,并且每个结果都包含通道和说话人 ID。

let conversationTranscriber = try! SPXConversationTranscriber(speechConfiguration: speechConfig, audioConfiguration: audioConfig!)

conversationTranscriber.addTranscribedEventHandler { transcriber, evt in
    guard let result = evt.result else {
        return
    }

    if result.reason == SPXResultReason.recognizedSpeech {
        print("TRANSCRIBED (channel \(result.channel), speaker \(result.speakerId ?? "")): \(result.text ?? "")")
    }
}

do {
    try conversationTranscriber.startTranscribingAsync { started, error in
        if let error = error {
            print("Could not start transcription: \(error)")
        } else if started {
            print("Transcription started")
        }
    }
} catch {
    print("Could not start transcription: \(error)")
}

转录完成后,停止转录器:

do {
    try conversationTranscriber.stopTranscribingAsync { stopped, error in
        if let error = error {
            print("Could not stop transcription: \(error)")
        } else if stopped {
            print("Transcription stopped")
        }
    }
} catch {
    print("Could not stop transcription: \(error)")
}

支持和不支持的功能

多通道听录适用于多个实时语音转文本功能,不支持其他功能。 下表汇总了当前支持。

Feature 支持
说话人分离
自定义语音
语义分割
TrueText
语言识别
多语言模型
流后优化
短语列表
发音评估

将多通道听录与分割相结合时,结果还包括说话人 ID。 用于分割结果的源通道元数据因语音 SDK 而异。 在同时使用频道元数据和说话人元数据之前,请先查阅你所用编程语言的相关指南。

不同通道的结果不能保证按完美的时间顺序到达,尤其是在语音跨通道重叠时。