BotFramework-WebChat icon indicating copy to clipboard operation
BotFramework-WebChat copied to clipboard

Speech api is not working perfectly on IOS devices.

Open UsamaAslam opened this issue 8 years ago • 8 comments

Hello. i am working on bot speech enable bot. Bot convert the voice to text but not convert text to speech in IOS devices in safari .In windows working perfectly in chrome and other .

Here is my Code :

var model = {
                          "userId": 'user',
                          "userName": 'User',
                          "botId": fulladdress,
                          "botIconUrl": "//bot-framework.azureedge.net/bot-icons-v1/bot-framework-default-8.png",
                          "botName": 'Vera',
                          "secret": "Secret",
                          "iconUrl": "//bot-framework.azureedge.net/bot-icons-v1/bot-framework-default-8.png",
                          "directLineUrl": "https://webchat.botframework.com/v3/directline",
                          "webSocketEnabled": "True"
                      };

                      var botConnection = new BotChat.DirectLine({
                          secret: model.secret,
                          token: model.token,
                          domain: model.directLineUrl,
                          webSocket: true,
                          sendTyping: true
                      });

                      BotChat.App({
                          sendTyping: true,
                          speechOptions: speechOptions,
                          directLine: botConnection,
                          user: { id: model.userId, name: model.userName },
                          bot: { id: model.botId, name: model.botName },                           
                          resize: 'window',
                      }, document.getElementById("BotChatElement"));

 const speechOptions = {
          speechRecognizer: new CognitiveServices.SpeechRecognizer({ subscriptionKey: 'Key' }),
          speechSynthesizer: new CognitiveServices.SpeechSynthesizer({
              gender: CognitiveServices.SynthesisGender.Female,
              subscriptionKey: 'Key',
              voiceName: 'Microsoft Server Speech Text to Speech Voice (en-US, ZiraRUS)'
          })
      };

UsamaAslam avatar Aug 18 '18 09:08 UsamaAslam

Check out issue #995 which is very similar. At the bottom is some javascript you can include that will make speech work with iOS devices.

rosskyl avatar Aug 27 '18 14:08 rosskyl

Still not working . I do it according to the link you share but not working . can you share working code or any guide line that can help that will be great .

UsamaAslam avatar Sep 10 '18 12:09 UsamaAslam

This is a stripped down version of what I use.

/*! modernizr 3.6.0 (Custom Build) | MIT *
 * https://modernizr.com/download/?-getusermedia-speechsynthesis !*/
!function (e, n, s) { function i(e, n) { return typeof e === n } function o() { var e, n, s, o, a, f, d; for (var c in t) if (t.hasOwnProperty(c)) { if (e = [], n = t[c], n.name && (e.push(n.name.toLowerCase()), n.options && n.options.aliases && n.options.aliases.length)) for (s = 0; s < n.options.aliases.length; s++)e.push(n.options.aliases[s].toLowerCase()); for (o = i(n.fn, "function") ? n.fn() : n.fn, a = 0; a < e.length; a++)f = e[a], d = f.split("."), 1 === d.length ? Modernizr[d[0]] = o : (!Modernizr[d[0]] || Modernizr[d[0]] instanceof Boolean || (Modernizr[d[0]] = new Boolean(Modernizr[d[0]])), Modernizr[d[0]][d[1]] = o), r.push((o ? "" : "no-") + d.join("-")) } } var t = [], a = { _version: "3.6.0", _config: { classPrefix: "", enableClasses: !0, enableJSClass: !0, usePrefixes: !0 }, _q: [], on: function (e, n) { var s = this; setTimeout(function () { n(s[e]) }, 0) }, addTest: function (e, n, s) { t.push({ name: e, fn: n, options: s }) }, addAsyncTest: function (e) { t.push({ name: null, fn: e }) } }, Modernizr = function () { }; Modernizr.prototype = a, Modernizr = new Modernizr, Modernizr.addTest("speechsynthesis", "SpeechSynthesisUtterance" in e), Modernizr.addTest("getUserMedia", "mediaDevices" in navigator && "getUserMedia" in navigator.mediaDevices); var r = []; o(), delete a.addTest, delete a.addAsyncTest; for (var f = 0; f < Modernizr._q.length; f++)Modernizr._q[f](); e.Modernizr = Modernizr }(window, document);

// Necessary for safari
// Safari will only speak after speaking from a button click
var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

function SpeakText() {
    var msg = new SpeechSynthesisUtterance();
    window.speechSynthesis.speak(msg);

    document.getElementsByClassName("wc-mic")[0].removeEventListener("click", SpeakText);
}

if (isSafari) {

    window.addEventListener("load", function () {
        document.getElementsByClassName("wc-mic")[0].addEventListener("click", SpeakText);
    });
}

// Needed to change between the two audio contexts
var AudioContext = window.AudioContext || window.webkitAudioContext;

// Sets the old style getUserMedia to use the new style that is supported in more browsers even though the framework uses the new style
if (window.navigator.mediaDevices.getUserMedia && !window.navigator.getUserMedia) {
    window.navigator.getUserMedia = function (constraints, successCallback, errorCallback) {
        window.navigator.mediaDevices.getUserMedia(constraints)
            .then(function (e) {
                successCallback(e);
            })
            .catch(function (e) {
                errorCallback(e);
            });
    };
}

const params = BotChat.queryParams(location.search);

// Needed to prevent the input hint from being Expecting Input
if (isSafari)
    document.getElementById("userName").value = document.getElementById("userName").value + ":ios";

const user = {
    id: document.getElementById("userId").value,
    name: document.getElementById("userName").value
};

const bot = {
    id: params['botid'] || 'botid',
    name: params['botname'] || 'botname'
};

window.botchatDebug = params['debug'] && params['debug'] === 'true';

var speechOptions;
if (Modernizr.speechsynthesis) {
    speechOptions = {
        speechRecognizer: new CognitiveServices.SpeechRecognizer({
            fetchCallback: function (authFetchEventId) { return getBingToken() },
            fetchOnExpiryCallback: function (authFetchEventId) { getBingToken() }
        }),
        speechSynthesizer: new BotChat.Speech.BrowserSpeechSynthesizer()
    };
}
else if (Modernizr.getusermedia) {
    speechOptions = {
        speechRecognizer: new CognitiveServices.SpeechRecognizer({
            fetchCallback: function (authFetchEventId) { return getBingToken() },
            fetchOnExpiryCallback: function (authFetchEventId) { getBingToken() }
        }),
        speechSynthesizer: null
    };
}
else {
    speechOptions = null;
}

var conversationId = getCookie("conversationId");
var botToken = getCookie("conversationToken");

var botConnection = new BotChat.DirectLine({
    domain: params['domain'],
    token: document.getElementById("directLineToken").value,
    webSocket: params['webSocket'] && params['webSocket'] === 'true' // defaults to true
});

BotChat.App({
    bot: bot,
    locale: params['locale'],
    resize: 'detect',
    speechOptions: speechOptions,
    user: user,
    botConnection: botConnection
}, document.getElementById('BotChatGoesHere'));

rosskyl avatar Sep 11 '18 15:09 rosskyl

I'm creating a bot which accept text and voice input and also can answer in both mode. The bot works really good but i have to click always the button of microphone to speak with the bot. Do you know it is possible to make microphone always on and to recognize the voice without clicking the button of microphone ?

@rosskyl

UsamaAslam avatar Oct 25 '18 16:10 UsamaAslam

Because of the way iOS is designed you need to click on the microphone each time. However, with other browsers if you set an input hint of ExpectingInput on each message it will listen after speaking.

rosskyl avatar Oct 25 '18 16:10 rosskyl

@rosskyl can yo share code example for better understanding? how can i set input hint as ExpectingInput on each message,

Thanks in advance.

UsamaAslam avatar Oct 25 '18 19:10 UsamaAslam

Still waiting for you comment @rosskyl

thanks

UsamaAslam avatar Oct 26 '18 12:10 UsamaAslam

This is what I am using to set the speak attribute and the input hint of each message.

public class TextToSpeakActivityMapper : IMessageActivityMapper
{
    public IMessageActivity Map(IMessageActivity message)
    {
        IMessageActivity initialMessage = message;

        try
        {
            if (message.Type == ActivityTypes.Message)
            {
                bool ignoredSpeak = false;
                if (string.IsNullOrEmpty(message.Speak))
                {
                    if (string.IsNullOrEmpty(message.Text))
                    {
                        var attachment = message.Attachments[0].Content as HeroCard; 
                        if (attachment != null)
                            message.Speak = DialogHelper.ConvertTextToSpeechText(attachment.Text);
                    }
                    else
                        message.Speak = DialogHelper.ConvertTextToSpeechText(message.Text);

                    message.Speak = message.Speak.Trim();

                }
                else if (string.IsNullOrWhiteSpace(message.Speak))
                {
                    message.Speak = null;
                }

                if ( ((!string.IsNullOrEmpty(message.Speak) && (message.Speak.EndsWith("?") || message.Speak.StartsWith("Is this your selection?")))
                     || (!string.IsNullOrEmpty(message.Text) && message.Text.EndsWith("?")))
                    && message.InputHint == null)
                    message.InputHint = InputHints.ExpectingInput;

                //IOs won't work with expecting input
                if (message.Recipient.Name.EndsWith(":ios"))
                    message.InputHint = InputHints.AcceptingInput;
            }

            return message;
        }
        catch (Exception)
        {
            return initialMessage;
        }
    }
}

Then you need to register it in your global.asax.cs

protected void Application_Start()
{
    GlobalConfiguration.Configure(WebApiConfig.Register);
    AutoMapperConfig.RegisterMappings();

    Conversation.UpdateContainer(
    builder =>
    {
        builder.RegisterModule(new AzureModule(Assembly.GetExecutingAssembly()));
        builder.RegisterModule<GlobalMessageHandlersBotModule>();

        // Bot Storage: Here we register the state storage for your bot. 
        // Default store: volatile in-memory store - Only for prototyping!
        // We provide adapters for Azure Table, CosmosDb, SQL Azure, or you can implement your own!
        // For samples and documentation, see: [https://github.com/Microsoft/BotBuilder-Azure](https://github.com/Microsoft/BotBuilder-Azure)
        //var store = new InMemoryDataStore();

        // Other storage options
        string connectionString = ConfigurationManager.ConnectionStrings["StateDataStore"].ConnectionString;
        var store = new TableBotDataStore(connectionString); // requires Microsoft.BotBuilder.Azure Nuget package 
        // var store = new DocumentDbBotDataStore("cosmos db uri", "cosmos db key"); // requires Microsoft.BotBuilder.Azure Nuget package 

        builder.Register(c => store)
            .Keyed<IBotDataStore<BotData>>(AzureModule.Key_DataStore)
            .AsSelf()
            .SingleInstance();

        builder.RegisterType<TextToSpeakActivityMapper>()
               .AsImplementedInterfaces()
               .SingleInstance();
    });
}

An alternative is to create an activity and set the speak and input hint on it and send that rather than sending text. For example,

await context.PostAsync("Hello world");

becomes

Activity reply = ((Activity)context.Activity).CreateReply();
reply.Type = ActivityTypes.Message;
reply.Name = "Hello world";
reply.Speak = "Hello world";
reply.InputHint = InputHints.ExpectingInput;
await context.PostAsync(reply);

rosskyl avatar Oct 26 '18 14:10 rosskyl