Azure JavaScript TTS-SDK for getting result as an in-memory stream ERROR - microsoft-cognitive

audioData: undefined,
errorDetails: "Unable to contact server. StatusCode: 500,
ErrorDetails: "Unable to contact server. StatusCode: 500, undefin…external_ocsp_ocsp.Agent is not a constructor",
//code
synthesizeSpeech() {
let that = this;
const speechConfig = SpeechConfig.fromSubscription(
"********",
"********"
);
speechConfig.speechSynthesisLanguage = "zh-CN";
const synthesizer = new SpeechSynthesizer(speechConfig);
var soundContext = undefined;
try {
var AudioContext = window.AudioContext ||window.webkitAudioContext || false;
if(AudioContext){
soundContext = new AudioContext();
}
} catch (err) {
console.log(err)
}
synthesizer.speakTextAsync(
"你好你好你好你好你好你好你好.",
result => {
console.log(result)
if(result.audioData && soundContext){
var source = soundContext.createBufferSource();
soundContext.decodeAudioData(result.audioData,function(newBuffer){
source.buffer = newBuffer;
source.connect(soundContext.destination);
source.start(0);
})
}
synthesizer.close();
},
error => {
console.log(error);
synthesizer.close();
}
);
},

This is fixed in Microsoft Azure Cognitive Services Speech SDK for JavaScript v1.12, which will be released recently. You can download the compiled js file after the release or you can compile it from the master of the sdk repo.

Related

hapi server : when i request with POST method, hapi server responding with null, but working fine in localhost

using hapi server -v = 16.7
joi -v = 10.6
deployed in aws ec2, nginx reverse proxy
Server Code in server.js:
'use strict';
//let newrelic = require('newrelic');
let Hapi = require('hapi');
let Routes = require('./Routes');
let Plugins = require('./Plugins');
let Bootstrap = require('./Utils/BootStrap');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
const Inert = require('inert');
const Vision = require('vision');
const HapiSwagger = require('hapi-swagger');
const Pack = require('./package');
const Config = require('./Config');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const server = new Hapi.Server();
server.connection({
port: Config.dbConfig.config.PORT,
routes: {cors: true}
});
let mongoOpts = {
reconnectTries: 60,
reconnectInterval: 2000,
useMongoClient:true
};
mongoose.connect(Config.dbConfig.config.dbURI,mongoOpts, (err, res) => {
if (err) {
console.log("DB Error: ", err);
process.exit(1);
} else {
console.log('MongoDB Connected');
}
});
server.register([
Inert,
Vision,
{
'register': HapiSwagger,
'options': {
info: {
'title': Config.dbConfig.config.SWAGGERNAME,
'version': Pack.version,
description: '',
},
//documentationPath: '/',
tags:[
{
name: 'v2.1.0',
description: 'API'
}
],
grouping: 'tags',
},
}], (err) => {
server.start((err) => {
if (err) {
console.log("Server err----------->", err);
} else {
console.log('Server running at:', server.info.uri);
}
});
});
server.on('response', (request) => {console.log('response===>>>:');
if(request.url.path.startsWith('/panel')){
}
else {//console.log('HEADERS===========>:',request.headers);
/* console for checking the params in the request*/
console.log(request.info.remoteAddress + ': ' + request.method.toUpperCase() +
' ' + request.url.path + ' --> ' + request.response.statusCode);
console.log('Request payload:', request.payload);
}
});
process.on('uncaughtException', function (err) {
console.log(err);
});
server.register(Plugins, function (err) {
if (err) {
server.error('Error while loading plugins : ' + err)
} else {
server.log('info', 'Plugins Loaded')
}
});
server.register(Inert, function (err) {
if (err) {
throw err;
}
server.route(Routes);
});
server.route([
{
method: 'GET',
path: '/{param*}', /* show error page */
handler: function (req, res) {
res.file('./error.html')
}
},
{
path: "/panel/{path*}",
method: "GET",
handler: { /* open admin panel index from panel path*/
directory: {
path: ['./_admin'],
listing: false,
index: ['index.html']
}
}
}
]);
This is deployed in AWS-EC2, with Nginx reverse proxy.When we hit POST request with payload, working fine in localhost and saves data to MongoDB. But when we hit same POST method from another domain against ec2 deployed server, the below error is showing in pm2 logs. It seems its responding with null before running the controller.
Error in pm2 logs, when we hit POST method:
TypeError: Cannot read property 'statusCode' of null
at /var/www/html/vhosts/custom_BE_ecommerce/api/server.js:123:65
at Object.internals.handler (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:283:33)
at invoke (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:255:23)
at each (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:259:13)
at Object.exports.parallel (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/items/lib/index.js:70:13)
at Object.internals.emit (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:276:18)
at module.exports.internals.Server.internals.Podium._emit (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:156:15)
at each (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:197:47)
at Object.exports.parallel (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/items/lib/index.js:70:13)
at relay (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:198:15)
at Object.internals.emit (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:202:16)
at internals.emitEmitter (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:303:15)
at processTicksAndRejections (node:internal/process/task_queues:79:21)
Need help on this issue.

Cloud Functions bucket.upload() is not running at all

here is what I am trying to do using Firebase:
create a backup file from realtime database
upload to firebase storage
do this every morning
but I am having problem on number 2; after the log of back up file creation success, no other log appears, not even a failed message.
no log after file creation
Even worse is that it sometimes works, which makes me doubtful about the consistency of the functionality.
my code:
var promiseFileCreation = function(fileName, jsonBackup){
console.log("promiseFileCreation starting");
return new Promise(function (resolve, reject){
fs.writeFile('/tmp/'+fileName, jsonBackup, function(fs_err){
if(!fs_err){
resolve("File "+fileName+" creation success");
} else {
reject("File "+fileName+" creation failure: "+fs_err);
}
})
}).catch(function(error){
reject("FileCreation Error");
})
}
var promiseBucketUpload = function(fileName, fileDest){
console.log("promiseBucketUpload starting")
return new Promise(function (resolve, reject){
console.log("promiseBucketUpload promise starting")
bucket.upload('/tmp/'+fileName, { destination: fileDest }, function(upload_err){
if(!upload_err){
resolve("File "+fileName+" upload to "+fileDest+" success");
} else {
reject("File "+fileName+" upload to "+fileDest+" failure: "+upload_err);
}
})
}).catch(function(error){
reject("BucketUpload Error: "+error);
})
}
Promise.all([promiseText, promiseDate, promiseTitle, promiseLikedCount, promiseViewCount, promiseComments]).then(function (values){
var jsonPostObj = {
post: [],
counter: []
}
jsonPostObj.post.push({
date: values[1],
text: values[0],
title: values[2]
})
jsonPostObj.counter.push({
likedCount: values[3],
viewCount: values[4]
})
var jsonCommentsObj = JSON.parse(values[5]);
const jsonArchiveObj = {...jsonPostObj, ...jsonCommentsObj}
var jsonArchive = JSON.stringify(jsonArchiveObj);
const yesterday = getYesterdayDateFull();
var fileName = "archive_"+yesterday;
var fileDest = "history/"+yesterday.substring(0,4)+"/"+yesterday.substring(4,6)+"/"+fileName;
console.log("Archive file name: "+fileName);
console.log("Archive destination: "+fileDest);
promiseFileCreation(fileName, jsonArchive).then(function(resultSuccessFs){
console.log(resultSuccessFs);
// BUCKETUPLOAD here
promiseBucketUpload(fileName, fileDest).then(function(resultSuccessBucket){
console.log(resultSuccessBucket);
return promiseBackupResult(true);
}, function(resultFailureBucket){
console.log(resultFailureBucket);
return promiseBucketResult(false);
})
}, function(resultFailureFs){
console.log(resultFailureFs);
return promiseBackupResult(false);
});
}).catch(function(errPromiseAll){
console.log("Promise.all error: "+errPromiseAll);
return promiseBackupResult(false);
})
}
I removed unnecessary codes, like other promises. The file creation seems to work fine.
Does anyone see why bucket.upload() is not called at all? Thanks in advance.

upload image using file transfer ionic 3 not work on iOS

upload image using file transfer in ionic 3 works fine on android,
but give me error on iOS when try it in simulator ..
* this is the error:
My Ionic Code:
chooseImageFromGallery()
{
this.type="0"
const options: CameraOptions = {
quality: 60,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
saveToPhotoAlbum:true,
sourceType:0
}
this.camera.getPicture(options)
.then((imageData) => {
if (this.platform.is('ios'))
{
this.base64Image = imageData;
}
else
{
this.base64Image = imageData;
}
this.uploadimage(); // this function to upload img to server
},
(err) => {
}).then((path)=>{
})
}
uploadimage(){
this.photoSrc="";
this.translate.get("uploading Image...").subscribe(
value => {
this.sucesss=false
const fileTransfer: FileTransferObject = this.transfer.create();
let options: FileUploadOptions = {
fileKey: "file",
fileName:'test',
chunkedMode:false,
mimeType:"image/jpeg",
headers:{
Connection:"close"
},
httpMethod: "POST",
}
//------------ android ------------//
this.base64Image =this.base64Image
//------------ ios ------------//
//this.base64Image =this.base64Image.substring(28)
fileTransfer.upload(this.base64Image,encodeURI('mydomain/api/Product/upload'), options)
.then((data:any) => {
alert("upload success ")
}, (err) => {
this.translate.get( "error in upload Data").subscribe(
value => {
this.service.presentToast(value,2000)
}
)
})
})
}
using asp.net api2 .. My server Code :
[HttpPost]
[Route("upload")]
[AllowAnonymous]
public HttpResponseMessage uploadImage()
{
var request = HttpContext.Current.Request;
if (Request.Content.IsMimeMultipartContent())
{
foreach (string file in request.Files)
{
var postedFile = request.Files[file];
if (postedFile != null && postedFile.ContentLength > 0)
{
string root = HttpContext.Current.Server.MapPath("~/ServerImg");
root = root + "/" + postedFile.FileName;
postedFile.SaveAs(root);
//Save post to DB
return Request.CreateResponse(HttpStatusCode.Found, new
{
error = false,
status = "created",
path = root
});
}
else
{
return Request.CreateResponse(HttpStatusCode.NotFound, new
{
error = true
});
}
// var title = request.Params["title"];
}
// }
return null;
}
else
{
return Request.CreateResponse(HttpStatusCode.Forbidden, new
{
error = true
});
}
}
I spend more than 4 days.. but nothing is work for me ..
And this code works fine on Android but not iOS I don't know what's the wrong, I tried real iPhone and Xcode simulator and not worked
always upload error {"code":3... "http_status":500,..
Can anyone Help me please...

firebase reset password controller

Yesterday my app was launched, Ionic v1, and a few users entered the wrong password and can't log into the app.
The app uses firebase authentication. I have a __refs file that points to the database and have tried numerous things trying to get the reset to work.
I've tried referencing $firebaseAuth, of course my __refs, $firebase then use $firebase.auth()...
I didn't write the authentication of this app so I'm not real sure how it works. I'm hoping that someone can help me.
My reset controller
angular.module('formulaWizard').controller('ResetPasswordCtrl',
function($scope, $ionicLoading, $firebaseAuth, __Refs) {
$scope.user = {
email: ''
};
$scope.errorMessage = null;
var fbAuth = $firebaseAuth(__Refs.rootRef);
$scope.resetPassword = function() {
$scope.errorMessage = null;
$ionicLoading.show({
template: 'Please wait...'
});
fbAuth.sendPasswordResetEmail($scope.user.email)
.then(showConfirmation)
.catch(handleError);
};
function showConfirmation() {
$scope.emailSent = true;
$ionicLoading.hide();
}
function handleError(error) {
switch (error.code) {
case 'INVALID_EMAIL':
case 'INVALID_USER':
$scope.errorMessage = 'Invalid email';
break;
default:
$scope.errorMessage = 'Error: [' + error.code + ']';
}
$ionicLoading.hide();
}
});
My Refs file
angular.module('formulaWizard')
.factory('__Refs', function ($firebaseArray, $firebaseObject) {
// Might use a resource here that returns a JSON arrayf
var ref = new Firebase('https://firebasedatabase.com/');
return {
rootRef: ref,
customers: ref.child('customers'),
}
});
I can't take credit for the answer it was provide by Abimbola Idowu on HackHands.
Since I paid for the answer I thought I would share it with anyone else that might also be stumped by this.
$scope.resetPassword = function() {
$scope.errorMessage = null;
$ionicLoading.show({
template: 'Please wait...'
});
__Refs.rootRef.resetPassword({ email: $scope.user.email }, function(error) {
if (error === null) {
showConfirmation();
} else {
handleError()
}
});
};
This is the __refs service
angular.module('formulaWizard')
.factory('__Refs', function ($firebaseArray, $firebaseObject) {
// Might use a resource here that returns a JSON arrayf
var ref = new Firebase('https://firebasedatabase.com/');
return {
rootRef: ref,
}
});

How to do REAL Syncing Data With Firebase

I am learning how to “Syncing Data With Firebase Using Ionic Framework”, Here is the code of TodoController.
myApp.controller("TodoController", function($scope, $firebaseObject, $ionicPopup) {
$scope.list = function() {
fbAuth = fb.getAuth();
if(fbAuth) {
var syncObject = $firebaseObject(fb.child("users/" + fbAuth.uid));
syncObject.$bindTo($scope, "data");
}
}
$scope.create = function() {
$ionicPopup.prompt({
title: 'Enter a new TODO item',
inputType: 'text'
})
.then(function(result) {
if(result !== "") {
if($scope.data.hasOwnProperty("todos") !== true) {
$scope.data.todos = [];
}
$scope.data.todos.push({title: result});
} else {
console.log("Action not completed");
}
});
}
});
The problem is: list() get data from remote Firebase directly, it will not get data from local storage at first and update/sync the local data to remote Firebase(4-way Data-binding??), has Firebase any method to sync local(if wifi disconnected) and server(when wifi connected) data automatically???
Any help would be much appreciated. Best Regards.

Resources