Я создал Speech Cognitive services
на Azure
портале и хотел бы подписаться на это руководство. где-то в указанном руководстве есть что-то вроде следующего:
fetch('https://webchat-mockbot.azurewebsites.net/speechservices/token', { method: 'POST' })
.
У меня вопрос, на какой адрес заменить эту часть кода? Я пробовал несколько вещей, но безуспешно. Например, я попробовал https://westeurope.api.cognitive.microsoft.com/sts/v1.0/issuetoken
и попытался указать один из двух ключей, которые я вижу в разделе Keys and Endpoints
, в качестве параметра метода post
. Но это не сработало. Я даже пробовал использовать ключ подписки и регион, но это тоже не сработало. Возможно, я использовал неправильный синтаксис.
Буду признателен, если кто-нибудь сможет мне помочь.
Обновление: вот мой обновленный код, у которого все еще есть проблема с микрофоном:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Web Chat: Cognitive Services Speech Services using JavaScript</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script crossorigin="anonymous" src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
<style>
html,
body {
height: 100%;
}
body {
margin: 0;
}
#webchat {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="webchat" role="main"></div>
<script>
function createFetchSpeechServicesCredentials() {
let expireAfter = 0;
let lastPromise;
return () => {
const now = Date.now();
if (now > expireAfter) {
expireAfter = now + 300000;
lastPromise = fetch(
'https://westus.api.cognitive.microsoft.com/sts/v1.0/issueToken',
{ method: 'POST', headers: { 'Ocp-Apim-Subscription-Key': 'my_subscription-key-speech-services' } }
).then(
res => res.json(),
err => {
expireAfter = 0;
return Promise.reject(err);
}
);
}
return lastPromise;
};
}
const fetchSpeechServicesCredentials = createFetchSpeechServicesCredentials();
(async function () {
const res = await fetch('https://directline.botframework.com/v3/directline/tokens/generate',
{ method: 'POST', headers: { Authorization: 'Bearer My_direct_line_secret_key1' } });
const { token } = await res.json();
const webSpeechPonyfillFactory = await window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory({
credentials: fetchSpeechServicesCredentials
});
window.WebChat.renderWebChat(
{
directLine: window.WebChat.createDirectLine({ token }),
webSpeechPonyfillFactory
},
document.getElementById('webchat')
);
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
</script>
</body>
</html>
Для простоты копирую код, который сработал после долгого обсуждения с @Hury Shen:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Web Chat: Cognitive Services Speech Services using JavaScript</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script crossorigin="anonymous" src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
<style>
html,
body {
height: 100%;
}
body {
margin: 0;
}
#webchat {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="webchat" role="main"></div>
<script>
(async function () {
const res = await fetch('https://directline.botframework.com/v3/directline/tokens/generate', { method: 'POST', headers: { Authorization: 'Bearer my-directline-secret-key' } });
const { token } = await res.json();
let authorizationToken;
const tokenRes = await fetch(
'https://westeurope.api.cognitive.microsoft.com/sts/v1.0/issuetoken',
{ method: 'POST', headers: { 'Ocp-Apim-Subscription-Key': 'my-cognitive-services-subscription-key' } }
);
if (tokenRes.status === 200) {
region = 'westeurope',
authorizationToken = await tokenRes.text()
} else {
return (new Error('error!'))
}
const webSpeechPonyfillFactory = await window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory({
authorizationToken: authorizationToken,
region: region
});
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({ token }),
webSpeechPonyfillFactory: webSpeechPonyfillFactory
}, document.getElementById('webchat'));
})().catch(err => console.error(err));
</script>
</body>
</html>
С уважением, Ханна