빠른 시작: 다중 디바이스 대화
이 빠른 시작에서는 Speech SDK를 사용하여 번역 지원을 통해 새로운 다중 디바이스 대화를 만들고 기존 대화에 참여하는 방법을 알아봅니다.
참고 항목
Java, JavaScript, Objective-C 및 Swift용 Speech SDK는 다중 디바이스 대화를 지원하지만 아직 여기에 가이드를 포함하지 않았습니다.
GitHub에서 모든 Speech SDK C# 샘플을 보거나 다운로드할 수 있습니다.
필수 조건
시작하기 전에 다음을 확인해야 합니다.
샘플 코드 추가
Program.cs 열고 해당 코드의 모든 코드를 다음 코드로 바꿉다.
using Microsoft.CognitiveServices.Speech; using Microsoft.CognitiveServices.Speech.Audio; using Microsoft.CognitiveServices.Speech.Transcription; using System; using System.Threading.Tasks; namespace HelloWorld { class Program { static async Task Main(string[] args) { await CreateConversationAsync(); } static async Task CreateConversationAsync() { // Replace these values with the details of your Cognitive Speech subscription string subscriptionKey = "YourSubscriptionKey"; // Replace below with your region identifier from here: https://aka.ms/speech/sdkregion string region = "YourServiceRegion"; // Sets source and target languages. // Replace with the languages of your choice, from list found here: https://aka.ms/speech/sttt-languages string fromLanguage = "en-US"; string toLanguage = "de"; // Set this to the display name you want for the conversation host string displayName = "The host"; // Create the task completion source that will be used to wait until the user presses Ctrl + C var completionSource = new TaskCompletionSource<bool>(); // Register to listen for Ctrl + C Console.CancelKeyPress += (s, e) => { completionSource.TrySetResult(true); e.Cancel = true; // don't terminate the current process }; // Create an instance of the speech translation config var config = SpeechTranslationConfig.FromSubscription(subscriptionKey, region); config.SpeechRecognitionLanguage = fromLanguage; config.AddTargetLanguage(toLanguage); // Create the conversation using (var conversation = await Conversation.CreateConversationAsync(config).ConfigureAwait(false)) { // Start the conversation so the host user and others can join await conversation.StartConversationAsync().ConfigureAwait(false); // Get the conversation ID. It will be up to your scenario to determine how this is shared with other participants. string conversationId = conversation.ConversationId; Console.WriteLine($"Created '{conversationId}' conversation"); // At this point, you can use the conversation object to manage the conversation. // For example, to mute everyone else in the room you can call this method: await conversation.MuteAllParticipantsAsync().ConfigureAwait(false); // Configure which audio source you want to use. If you are using a text only language, you // can use the other overload of the constructor that takes no arguments var audioConfig = AudioConfig.FromDefaultMicrophoneInput(); using (var conversationTranslator = new ConversationTranslator(audioConfig)) { // You should connect all the event handlers you need at this point conversationTranslator.SessionStarted += (s, e) => { Console.WriteLine($"Session started: {e.SessionId}"); }; conversationTranslator.SessionStopped += (s, e) => { Console.WriteLine($"Session stopped: {e.SessionId}"); }; conversationTranslator.Canceled += (s, e) => { switch (e.Reason) { case CancellationReason.EndOfStream: Console.WriteLine($"End of audio reached"); break; case CancellationReason.Error: Console.WriteLine($"Canceled due to error. {e.ErrorCode}: {e.ErrorDetails}"); break; } }; conversationTranslator.ConversationExpiration += (s, e) => { Console.WriteLine($"Conversation will expire in {e.ExpirationTime.TotalMinutes} minutes"); }; conversationTranslator.ParticipantsChanged += (s, e) => { Console.Write("The following participant(s) have "); switch (e.Reason) { case ParticipantChangedReason.JoinedConversation: Console.Write("joined"); break; case ParticipantChangedReason.LeftConversation: Console.Write("left"); break; case ParticipantChangedReason.Updated: Console.Write("been updated"); break; } Console.WriteLine(":"); foreach (var participant in e.Participants) { Console.WriteLine($"\t{participant.DisplayName}"); } }; conversationTranslator.TextMessageReceived += (s, e) => { Console.WriteLine($"Received an instant message from '{e.Result.ParticipantId}': '{e.Result.Text}'"); foreach (var entry in e.Result.Translations) { Console.WriteLine($"\tTranslated into '{entry.Key}': '{entry.Value}'"); } }; conversationTranslator.Transcribed += (s, e) => { Console.WriteLine($"Received a transcription from '{e.Result.ParticipantId}': '{e.Result.Text}'"); foreach (var entry in e.Result.Translations) { Console.WriteLine($"\tTranslated into '{entry.Key}': '{entry.Value}'"); } }; conversationTranslator.Transcribing += (s, e) => { Console.WriteLine($"Received a partial transcription from '{e.Result.ParticipantId}': '{e.Result.Text}'"); foreach (var entry in e.Result.Translations) { Console.WriteLine($"\tTranslated into '{entry.Key}': '{entry.Value}'"); } }; // Enter the conversation to start receiving events await conversationTranslator.JoinConversationAsync(conversation, displayName).ConfigureAwait(false); // You can now send an instant message to all other participants in the room await conversationTranslator.SendTextMessageAsync("The instant message to send").ConfigureAwait(false); // If specified a speech to text language, you can start capturing audio await conversationTranslator.StartTranscribingAsync().ConfigureAwait(false); Console.WriteLine("Started transcribing. Press Ctrl + c to stop"); // At this point, you should start receiving transcriptions for what you are saying using the default microphone. Press Ctrl+c to stop audio capture await completionSource.Task.ConfigureAwait(false); // Stop audio capture await conversationTranslator.StopTranscribingAsync().ConfigureAwait(false); // Leave the conversation. After this you will no longer receive events await conversationTranslator.LeaveConversationAsync().ConfigureAwait(false); } // End the conversation await conversation.EndConversationAsync().ConfigureAwait(false); // Delete the conversation. Any other participants that are still in the conversation will be removed await conversation.DeleteConversationAsync().ConfigureAwait(false); } } } }
같은 파일에서
YourSubscriptionKey
문자열을 Cognitive Speech 구독 키로 바꿉니다.문자열
YourServiceRegion
을 구독과 연결된 지역으로 바꿉다.메뉴 모음에서 파일>모두 저장을 선택합니다.
애플리케이션을 빌드하고 실행하여 새 대화 만들기
메뉴 모음에서 빌드 솔루션 빌드>를 선택하여 애플리케이션을 빌드합니다. 이제 코드가 오류 없이 컴파일되어야 합니다.
디버그>시작 디버깅을 선택하거나 F5 키를 눌러 helloworld 애플리케이션을 시작합니다.
Started transcribing
메시지가 표시되면 말하기를 시작할 수 있습니다. 말하는 동안 전사가 표시됩니다.- 대화 코드를 다른 사용자와 공유하고 대화에 참여하는 경우 대화 내용도 표시됩니다.
말하기가 완료되면 Ctrl+C를 눌러 오디오 캡처를 중지하고 대화를 종료합니다.
애플리케이션을 빌드하고 실행하여 기존 대화에 조인
다음 함수를 복사하여 Program.cs 붙여넣습니다.
static async Task JoinConversationAsync(string conversationId) { // Set this to the display name you want for the participant string displayName = "participant"; // Set the speech to text, or text language you want to use string language = "en-US"; // Create the task completion source that will be used to wait until the user presses Ctrl + c var completionSource = new TaskCompletionSource<bool>(); // Register to listen for Ctrl+C Console.CancelKeyPress += (s, e) => { completionSource.TrySetResult(true); e.Cancel = true; // don't terminate the current process }; // As a participant, you don't need to specify any subscription key, or region. You can directly create // the conversation translator object var audioConfig = AudioConfig.FromDefaultMicrophoneInput(); using (var conversationTranslator = new ConversationTranslator(audioConfig)) { // Register for any events you are interested here. For now let's just register for // transcription, and instant message events conversationTranslator.TextMessageReceived += (s, e) => { Console.WriteLine($"Received an instant message from '{e.Result.ParticipantId}': '{e.Result.Text}'"); foreach (var entry in e.Result.Translations) { Console.WriteLine($"\tTranslated into '{entry.Key}': '{entry.Value}'"); } }; conversationTranslator.Transcribed += (s, e) => { Console.WriteLine($"Received a transcription from '{e.Result.ParticipantId}': '{e.Result.Text}'"); foreach (var entry in e.Result.Translations) { Console.WriteLine($"\tTranslated into '{entry.Key}': '{entry.Value}'"); } }; conversationTranslator.Transcribing += (s, e) => { Console.WriteLine($"Received a partial transcription from '{e.Result.ParticipantId}': '{e.Result.Text}'"); foreach (var entry in e.Result.Translations) { Console.WriteLine($"\tTranslated into '{entry.Key}': '{entry.Value}'"); } }; // To start receiving events, you will need to join the conversation await conversationTranslator.JoinConversationAsync(conversationId, displayName, language).ConfigureAwait(false); // You can now send an instant message await conversationTranslator.SendTextMessageAsync("Message from participant").ConfigureAwait(false); // Start capturing audio if you specified a speech to text language await conversationTranslator.StartTranscribingAsync().ConfigureAwait(false); Console.WriteLine("Started transcribing. Press Ctrl-C to stop"); // At this point, you should start receiving transcriptions for what you are saying using // the default microphone. Press Ctrl+C to stop audio capture await completionSource.Task.ConfigureAwait(false); // Stop audio capture await conversationTranslator.StopTranscribingAsync().ConfigureAwait(false); // Leave the conversation. You will stop receiving events after this await conversationTranslator.LeaveConversationAsync().ConfigureAwait(false); } }
함수에서 다음으로 대체
CreateConversationAsync();
합니다public static async Task Main(string[] args)
.// Set this to the conversation you want to join JoinConversationAsync("YourConversationId");
참가할 수 있는 대화를 만들어야 합니다.
- 브라우저를 시작하고 다음 https://translator.microsoft.com으로 이동합니다.
- "대화 시작"을 선택합니다.
- 사용 가능한 옵션 중 하나를 사용하여 로그인합니다.
- 이름(예: 호스트)을 입력합니다.
- 언어(예: 영어)를 선택합니다.
- Enter 단추를 선택합니다.
- 페이지 상단에 있는 대화 코드를 확인합니다.
팁
웹 페이지에서 복사 단추를 사용하는 경우 시작 시 제거
translate.it/
해야 합니다. 5자 문자 대화 ID(예: ABCDE)만 필요합니다.
Visual Studio로 돌아가서 문자열
YourConversationId
을 이전 단계에서 만든 대화 ID로 바꿉니다.메뉴 모음에서 빌드 솔루션 빌드>를 선택하여 애플리케이션을 빌드합니다. 이제 코드가 오류 없이 컴파일되어야 합니다.
디버그>시작 디버깅을 선택하거나 F5 키를 눌러 helloworld 애플리케이션을 시작합니다.
Started transcribing
메시지가 표시되면 말하기를 시작할 수 있습니다. 말하는 동안 전사가 표시됩니다.- 브라우저로 돌아가면 대화할 때 전사가 표시됩니다.
말하기가 완료되면 Ctrl+C를 눌러 오디오 캡처를 중지하고 대화를 종료합니다.
브라우저로 돌아가서 오른쪽 위 모서리에 있는 종료 단추를 사용하여 대화를 종료합니다.
다음 단계
GitHub에서 모든 Speech SDK C++ 샘플을 보거나 다운로드할 수 있습니다.
필수 조건
시작하기 전에 다음을 확인해야 합니다.
샘플 코드 추가
Visual Studio에서 소스 파일 helloworld.cpp 엽니다.
모든 코드를 다음 코드 조각으로 바꿉다.
#include "pch.h" #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <iostream> #include <thread> #include <future> #include <string> #include <speechapi_cxx.h> using namespace std::chrono_literals; using namespace Microsoft::CognitiveServices::Speech; using namespace Microsoft::CognitiveServices::Speech::Audio; using namespace Microsoft::CognitiveServices::Speech::Transcription; // Create a promise we will set when the user presses Ctrl-C std::promise<bool> promise; // Create the future we will use to wait for the promise to be fulfilled std::future<bool> future = promise.get_future(); void StartNewConversation() { // Set these std::string subscriptionKey("YourSubscriptionKey"); // Replace below with your own region identifier from here: https://aka.ms/speech/sdkregion std::string region("YourServiceRegion"); std::string speechLanguage("en-US"); // Create the conversation object you'll need to manage the conversation auto speechConfig = SpeechConfig::FromSubscription(subscriptionKey, region); speechConfig->SetSpeechRecognitionLanguage(speechLanguage); auto conversation = Conversation::CreateConversationAsync(speechConfig).get(); // Start the conversation so you and others can join conversation->StartConversationAsync().get(); // Get the conversation ID. It will be up to your scenario to determine how this is shared with other participants. std::cout << "Created conversation: " << conversation->GetConversationId() << std::endl; // You can now call various commands to manage the room. For example: conversation->MuteAllParticipantsAsync().get(); // Create the conversation translator you'll need to send audio, send IMs, and receive conversation events auto audioConfig = AudioConfig::FromDefaultMicrophoneInput(); auto conversationTranslator = ConversationTranslator::FromConfig(audioConfig); // Add any event handlers conversationTranslator->SessionStarted += [](const SessionEventArgs& args) { std::cout << "Session started " << args.SessionId << std::endl; }; conversationTranslator->SessionStopped += [](const SessionEventArgs& args) { std::cout << "Session stopped " << args.SessionId << std::endl; }; conversationTranslator->Canceled += [](const ConversationTranslationCanceledEventArgs& args) { switch (args.Reason) { case CancellationReason::EndOfStream: std::cout << "End of audio reached" << std::endl; break; case CancellationReason::Error: std::cout << "Canceled due to error. " << (long)args.ErrorCode << ": " << args.ErrorDetails << std::endl; break; } }; conversationTranslator->ConversationExpiration += [](const ConversationExpirationEventArgs& args) { std::cout << "Conversation will expire in " << args.ExpirationTime.count() << " minutes" << std::endl; }; conversationTranslator->ParticipantsChanged += [](const ConversationParticipantsChangedEventArgs& args) { std::cout << "The following participant(s) have "; switch (args.Reason) { case ParticipantChangedReason::JoinedConversation: std::cout << "joined"; break; case ParticipantChangedReason::LeftConversation: std::cout << "left"; break; case ParticipantChangedReason::Updated: std::cout << "been updated"; break; } std::cout << ":" << std::endl; for(std::shared_ptr<Participant> participant : args.Participants) { std::cout << "\t" << participant->DisplayName << std::endl; } }; conversationTranslator->Transcribing += [](const ConversationTranslationEventArgs& args) { std::cout << "Received a partial transcription from " << args.Result->ParticipantId << ": " << args.Result->Text << std::endl; for (const auto& entry : args.Result->Translations) { std::cout << "\t" << entry.first << ": " << entry.second << std::endl; } }; conversationTranslator->Transcribed += [](const ConversationTranslationEventArgs& args) { std::cout << "Received a transcription from " << args.Result->ParticipantId << ": " << args.Result->Text << std::endl; for (const auto& entry : args.Result->Translations) { std::cout << "\t" << entry.first << ": " << entry.second << std::endl; } }; conversationTranslator->TextMessageReceived += [](const ConversationTranslationEventArgs& args) { std::cout << "Received an instant message from " << args.Result->ParticipantId << ": " << args.Result->Text << std::endl; for (const auto& entry : args.Result->Translations) { std::cout << "\t" << entry.first << ": " << entry.second << std::endl; } }; // Join the conversation so you can start receiving events conversationTranslator->JoinConversationAsync(conversation, "Test Host").get(); // Send an instant message conversationTranslator->SendTextMessageAsync("This is a short test message").get(); // Start sending audio conversationTranslator->StartTranscribingAsync().get(); std::cout << "Started transcribing. Press Ctrl + C to stop" << std::endl; future.get(); // wait for Ctrl - C to be pressed // Stop audio capture conversationTranslator->StopTranscribingAsync().get(); // Leave the conversation. You will stop receiving events conversationTranslator->LeaveConversationAsync().get(); // Once you are done, remember to delete the conversation. conversation->EndConversationAsync().get(); // You will not be able to rejoin after this conversation->DeleteConversationAsync().get(); // All participants still in the room will be ejected } int main() { // Register a handler for the Ctrl - C callback SetConsoleCtrlHandler( [](DWORD dwCtrlType) -> BOOL { if (dwCtrlType == CTRL_C_EVENT) { // Signal that the user has pressed ctrl + C promise.set_value(true); return TRUE; } return FALSE; }, TRUE); StartNewConversation(); }
동일한 파일에서
YourSubscriptionKey
문자열을 구독 키로 바꿉니다.문자열
YourServiceRegion
을 구독과 연결된 지역으로 바꿉다.메뉴 모음에서 파일>모두 저장을 선택합니다.
애플리케이션을 빌드하고 실행하여 새 대화 만들기
메뉴 모음에서 빌드 솔루션 빌드>를 선택하여 애플리케이션을 빌드합니다. 이제 코드가 오류 없이 컴파일되어야 합니다.
디버그>시작 디버깅을 선택하거나 F5 키를 눌러 helloworld 애플리케이션을 시작합니다.
Started transcribing
메시지가 표시되면 말하기를 시작할 수 있습니다. 말하는 대로 전사가 나타납니다.- 대화 코드를 다른 사용자와 공유하고 대화에 참여하는 경우 대화 내용도 표시됩니다.
말하기가 완료되면 키보드에서 Ctrl+C를 눌러 오디오 캡처를 중지합니다.
참고 항목
Visual Studio에서 다음과 유사한 예외에 대한 메시지가 표시되면
Exception thrown at 0x76EB90BF (KernelBase.dll) in helloworld.exe: 0x40010005: Control-C.
무시해도 됩니다.
F5를 눌러 계속합니다.
애플리케이션을 빌드하고 실행하여 기존 대화에 조인
다음 함수를 복사하여 함수 바로 앞에 helloworld.cpp 붙여넣습니다
int main()
.void JoinExistingConversation(const std::string& conversationId) { std::string speechLanguage("en-US"); // You'll now need to create a ConversationTranslator to send audio, send IMs, and receive conversation events auto audioConfig = AudioConfig::FromDefaultMicrophoneInput(); auto conversationTranslator = ConversationTranslator::FromConfig(audioConfig); // Attach event handlers here. For example: conversationTranslator->Transcribing += [](const ConversationTranslationEventArgs& args) { std::cout << "Received a partial transcription from " << args.Result->ParticipantId << ": " << args.Result->Text << std::endl; for (const auto& entry : args.Result->Translations) { std::cout << "\t" << entry.first << ": " << entry.second << std::endl; } }; conversationTranslator->Transcribed += [](const ConversationTranslationEventArgs& args) { std::cout << "Received a transcription from " << args.Result->ParticipantId << ": " << args.Result->Text << std::endl; for (const auto& entry : args.Result->Translations) { std::cout << "\t" << entry.first << ": " << entry.second << std::endl; } }; conversationTranslator->TextMessageReceived += [](const ConversationTranslationEventArgs& args) { std::cout << "Received an instant message from " << args.Result->ParticipantId << ": " << args.Result->Text << std::endl; for (const auto& entry : args.Result->Translations) { std::cout << "\t" << entry.first << ": " << entry.second << std::endl; } }; // Join the conversation conversationTranslator->JoinConversationAsync(conversationId, "participant", speechLanguage).get(); // Start sending audio conversationTranslator->StartTranscribingAsync().get(); std::cout << "Started transcribing. Press Ctrl + C to stop" << std::endl; future.get(); // wait for Ctrl - C to be pressed // Stop audio capture conversationTranslator->StopTranscribingAsync().get(); // Once you are done, leave the conversation conversationTranslator->LeaveConversationAsync().get(); }
함수에서 다음으로 대체
StartNewConversation();
합니다int main()
.// Set this to the conversation you want to join JoinExistingConversation("YourConversationId");
참가할 수 있는 대화를 만들어야 합니다.
- 브라우저를 시작하고 다음 https://translator.microsoft.com으로 이동합니다.
- "대화 시작"을 선택합니다.
- 사용 가능한 옵션 중 하나를 사용하여 로그인합니다.
- 이름(예: 호스트)을 입력합니다.
- 언어(예: 영어)를 선택합니다.
- Enter 단추를 선택합니다.
- 페이지 상단에 있는 대화 코드를 확인합니다.
팁
웹 페이지에서 복사 단추를 사용하는 경우 시작 시 제거
translate.it/
해야 합니다. 5자 문자 대화 ID(예: ABCDE)만 필요합니다.
Visual Studio로 돌아가서
int main()
함수의YourConversationId
를 이전 단계의 대화 ID로 바꿉니다.메뉴 모음에서 빌드 솔루션 빌드>를 선택하여 애플리케이션을 빌드합니다. 코드는 오류 없이 컴파일됩니다.
디버그>시작 디버깅을 선택하거나 F5 키를 눌러 helloworld 애플리케이션을 시작합니다.
Started transcribing
메시지가 표시되면 말하기를 시작할 수 있습니다. 말하는 동안 전사가 표시됩니다.- 브라우저로 돌아가면 대화할 때 전사가 표시됩니다.
말하기가 완료되면 Ctrl+C를 눌러 오디오 캡처를 중지하고 대화를 종료합니다.
참고 항목
Visual Studio에서 다음과 유사한 예외에 대한 메시지가 표시되면
Exception thrown at 0x76EB90BF (KernelBase.dll) in helloworld.exe: 0x40010005: Control-C.
무시해도 됩니다.
F5를 눌러 계속합니다.브라우저로 돌아가서 오른쪽 위 모서리에 있는 종료 단추를 사용하여 대화를 종료합니다.