How to add wavesurfer.js microphone plugin - angular6

am working angular cli am trying to add microphone plugin is not working .Let me know how to add the package.
this my code
angular.json file
scripts": ["node_modules/jquery/dist/jquery.min.js",
"node_modules/wavesurfer.js/dist/wavesurfer.js",
"node_modules/wavesurfer.js/dist/plugin/wavesurfer.microphone.min.js"]
}
****This is My .ts file where am getting error could somebody help me****
import MicrophonePlugin from 'wavesurfer.js/dist/plugin/wavesurfer.microphone.min.js';
import * as $ from 'jquery';
import * as WaveSurfer from 'wavesurfer.js';
public start() {
let wavesurfer= WaveSurfer.create({
container: '#waveform',
waveColor: 'violet',
progressColor: 'purple',
plugins: [MicrophonePlugin.create()]
});
wavesurfer.microphone.on('deviceReady', function() {
console.info('Device ready!');
});
wavesurfer.microphone.on('deviceError', function(code) {
console.warn('Device error: ' + code);
})
let microphone = WaveSurfer.Microphone; // Here am getting error microphone is undefined
microphone.create({
wavesurfer: wavesurfer
});
microphone.on('deviceReady', function(stream) {
console.log('Device ready!', stream);
});
microphone.on('deviceError', function(code) {
console.warn('Device error: ' + code);
});
// start the microphone
microphone.start();
}

There you go:
import MicrophonePlugin from 'wavesurfer.js/dist/plugin/wavesurfer.microphone.min.js';
import * as $ from 'jquery';
import * as WaveSurfer from 'wavesurfer.js';
public start() {
let wavesurfer= WaveSurfer.create({
container: '#waveform',
waveColor: 'violet',
progressColor: 'purple',
plugins: [ MicrophonePlugin.create() ]
});
wavesurfer.microphone.on('deviceReady', function (stream) {
console.info('Device ready!', stream);
});
wavesurfer.microphone.on('deviceError', function(code) {
console.warn('Device error: ' + code);
})
let microphone = wavesurfer.microphone; // you had the case wrong!
/*
You have already done all that stuff above
microphone.create({
wavesurfer: wavesurfer
});
microphone.on('deviceReady', function(stream) {
console.log('Device ready!', stream);
});
microphone.on('deviceError', function(code) {
console.warn('Device error: ' + code);
});
*/
// start the microphone
microphone.start();
}
If you want to do something with the stream (to play it back on another wavesurfer or to send it to a server), you can use a MediaRecorder:
wavesurfer: Object;
mediaRecorder: Object;
recordingBlob: Object;
public start() {
...
this.recordingBlob = null;
this.wavesurfer.microphone.on('deviceReady', function (stream) {
this.mediaRecorder = new MediaRecorder(stream);
this.mediaRecorder.onondataavailable = event => {
this.recordingBlob = event.data;
};
this.mediaRecorder.start();
});
...
}
public stop() {
if (!this.mediaRecorder || !this.wavesurfer) return;
this.mediaRecorder.stop();// triggers mediaRecorder.onondataavailable
this.mediaRecorder = null;
this.wavesurfer.stop();
}

Related

Nativescript : camera photo asset with nativescript-ocr

I'm trying to take a picture with the nativescript camera module and to run
the nativescript-ocr module (https://github.com/EddyVerbruggen/nativescript-ocr) on it .
Here is my code :
public saveToGallery: boolean = true;
public keepAspectRatio: boolean = true;
public width: number = 300;
public height: number = 300;
private ocr: OCR;
constructor() {
this.ocr = new OCR();
}
ngOnInit(): void {
}
onTakePhoto() {
let options = {
width: this.width,
height: this.height,
keepAspectRatio: this.keepAspectRatio,
saveToGallery: this.saveToGallery
};
takePicture(options).
then((imageAsset) => {
console.log("Result is an image asset instance");
let img: ImageSource = new ImageSource();
img.fromAsset(imageAsset).then((success) => {
if (success) {
this.ocr.retrieveText({
image: img,
whitelist: "ABCDEF",
blacklist: "0123456789",
onProgress: (percentage: number) => {
console.log(`Decoding progress: ${percentage}%`);
}
}).then(
(result: RetrieveTextResult) => {
console.log(`Result: ${result.text}`);
}, (error: string) => {
console.log(`Error: ${error}`);
})
}
});
}).catch((err) => {
console.log("Error -> " + err.message);
});
}
onRequestPermissions() {
requestPermissions();
}
}
Camera plugin works fine, takes and saves a picture, but when i'm running onTakePhoto i get this error message :
"Error in ocr.retrieveText: Error: java.lang.IllegalArgumentException: Data path does not exist!"
i'm not sure to use the .fromAsset the right way,
but i try a lot of thing to solve this problem
what i'm doing wrong?
Resolve : i didn't create corectly my tesseract/tessdata folder

TypeScript/Angular: Cannot find name 'XXX'

I have two functions in the same TypeScript component. When I try to call one already declared, VSCode reports that it "[ts] Cannot find name 'XXX'.".
As requested by Tiep Phan, this is the full code:
liveSearchFMs(input: any) {
this._ectmService.getFMsFromUserSearch(input).subscribe(
fanmissions => this.fanmissions = fanmissions,
error => this.errorMessage = <any>error
);
}
timeout(input) {
var enteredValue = input;
var timeout = null;
clearTimeout(timeout);
timeout = setTimeout(function () {
this.liveSearchFMs(enteredValue);
}, 1000);
}
I guess you wanna create something like this
export class EctmListComponent implements OnInit {
// other code
private timeoutTracker;
timeout(input) {
if (this.timeoutTracker) {
clearTimeout(this.timeoutTracker);
}
//use arrow function instead
this.timeoutTracker = setTimeout(() => {
this.liveSearchFMs(input);
}, 1000);
// or store context first
/*
const ctx = this;
this.timeoutTracker = setTimeout(function() {
ctx.liveSearchFMs(input);
}, 1000);
*/
// or using bind method
/*
this.timeoutTracker = setTimeout((function() {
this.liveSearchFMs(input);
}).bind(this), 1000);
*/
}
}
You need to use this keyword. so this.liveSearchFMs

Inserting specific file at index of a stream

Basicly this gulp script finds the 'file1,file2,file3' in a folder, builds its dependencies (which are in the same folder) and add it all to 1 file.
Now, my problem is, i have a custom file which i have to put in after file2. How can i achieve this?
function gatherAMD(stream, file) {
var moduleId = file.path.match(/file\.(.+)\.js/)[1];
return stream.pipe(amdOptimize(`file.${moduleId}`, {
baseUrl: "fileslocation/location",
exclude: [ 'jquery' ]
}));
}
gulp.task("js", function() {
var included = [];
var files = "file1,file2,file3"
var stream = null;
if (files.indexOf(",") == -1) {
stream = gulp.src('fileslocation/location/file.'+ files+ '.js', { base: "fileslocation/location"});
} else {
stream = gulp.src(`fileslocation/location/file.{${files}}.js`, { base: "fileslocation/location"});
}
return stream.pipe(debug())
.pipe(foreach(gatherAMD))
.pipe(filter(function(file) {
if (included.indexOf(file.path) === -1) {
included.push(file.path);
return true;
} else {
return false;
}
}))
.pipe(concat({path: 'fileslocation/custom.js', base: 'fileslocation'}))
.pipe(gulp.dest("fileslocation"));
});
You can probably use map for checking the current file in the stream, and then adding it from some logic and then using gulp-inject to add a file to the stream.
Something like,
return stream.pipe(debug())
.pipe(foreach(gatherAMD))
.pipe(filter(function(file) {
if (included.indexOf(file.path) === -1) {
included.push(file.path);
return true;
} else {
return false;
}
}))
.pipe(map(function(file, callback) {
if (file.relative === 'file2.js') {
// inject file to the stream here
}
callback(null, file);
}))
.pipe(concat({path: 'fileslocation/custom.js', base: 'fileslocation'}))
.pipe(gulp.dest("fileslocation"));

Setting data in viewModel knockoutjs from html5 websocket

I am trying to create knockout.js component that is getting data from HTML5 Websocket. Websocket code is in separate script e.g. util.js. I am able to connect and get data from socket, but dont know how correctly to set corresponding property in component`s ViewModel.
Websocket - util.js:
var options = {
server: '127.0.0.1',
port: '12345'
};
var socket, loadedFlag;
var timeout = 2000;
var clearTimer = -1;
var data = {};
function handleErrors(sError, sURL, iLine)
{
return true;
};
function getSocketState()
{
return (socket != null) ? socket.readyState : 0;
}
function onMessage(e)
{
data=$.parseJSON(e.data);
// ???? Is it possible to have here something like
// ???? viewModel.getDataWS1(data);
}
function onError()
{
clearInterval(clearTimer);
socket.onclose = function () {
loadedFlag = false;
};
clearTimer = setInterval("connectWebSocket()", timeout);
}
function onClose()
{
loadedFlag = false;
clearInterval(clearTimer);
clearTimer = setInterval("connectWebSocket()", timeout);
}
function onOpen()
{
clearInterval(clearTimer);
console.log("open" + getSocketState());
}
function connectWebSocket()
{
if ("WebSocket" in window)
{
if (getSocketState() === 1)
{
socket.onopen = onOpen;
clearInterval(clearTimer);
console.log(getSocketState());
}
else
{
try
{
host = "ws://" + options.server + ":" + options.port;
socket = new WebSocket(host);
socket.onopen = onOpen;
socket.onmessage = function (e) {
onMessage(e);
};
socket.onerror = onError;
socket.onclose = onClose;
}
catch (exeption)
{
console.log(exeption);
}
}
}
}
Component (productDisplay.js) - creating so that is can be used on multiple pages:
define([
'jquery',
'app/models/productDisplayModel',
'knockout',
'mapping',
'socket'
],
function ($, model, ko, mapping) {
ko.components.register('product', {
viewModel: {require: 'app/models/productModel'},
template: {require: 'text!app/views/product.html'}
});
});
Product ViewModel (productModel.js) - where I struggle to set viewModel property to data from websocket:
var viewModel = {};
define(['knockout', 'mapping', 'jquery'], function (ko, mapping, $) {
function Product(name, rating) {
this.name = name;
this.userRating = ko.observable(rating || null);
}
function MyViewModel() {
this.products = ko.observableArray(); // Start empty
}
MyViewModel.prototype.getDataWS1 = function () {
//Websocket has not connected and returned data yet, so data object is empty
// ???? Is there anyway I can add something like promise so that the value is set once socket is connected?
this.products(data);
};
// apply binding on page load
$(document).ready(function () {
connectToServer1();
viewModel = new MyViewModel();
ko.applyBindings(viewModel);
viewModel.getDataWS1();
});
});
Thank you for any ideas.
You can update an observable when you get a message in the following manner:
util.js
function onMessage(e) {
var productData = $.parseJSON(e.data);
viewModel.addNewProduct(productData);
}
productModel.js
function Product(name, rating) {
this.name = name;
this.userRating = ko.observable(rating || null);
}
function MyViewModel() {
this.products = ko.observableArray(); // Start empty
}
MyViewModel.prototype.addNewProduct(product) {
var newProduct = new Product(product.name, product.rating);
this.products.push(newProduct);
}
Basically the idea is that when you get a message (in onMessage function), you will parse the data and call a function in your viewmodel to add the message data to the viewmodel properties (observables, observableArrays, etc.)

ActionScript 3 Error #1009 null object reference

I'm having some errors with a command system I built for my flash project. One of the commands is intro which essentially restarts the project, or is meant to (The intro starts at frame 0 of the first scene). But when it runs a reference error is thrown on what I have determined to be line 21 (Through commenting code out until it no longer errors) which is the thisRef.gotoAndPlay line of the intro function.
Here is my code:
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.system.fscommand;
import flash.events.KeyboardEvent;
import flash.media.Sound;
public class Main extends MovieClip {
/* The real frame number */
public var realFrameNo:int = 0;
/* Whether startup has been ran or not */
public var startupRan:Boolean = false;
/* Whether or not the beggining text is there */
public var placeholderPresent:Boolean = true;
/* Commands recognized by the computer [command:string,handler:void] */
public var commandList = new Array(["intro",function(thisRef:Main) {
gotoAndPlay(0,"Intro");
}],
["exit",function(thisRef:Main) {
fscommand("quit");
}]);
/* Helper functions */
public function isAlphabetic(value:String):Boolean
{
var result:String = value.match(/[a-zA-Z]*/)[0];
return value.length == result.length;
}
public function getSceneNo():int
{
return (realFrameNo > 0 ? Math.floor( (realFrameNo / stage.frameRate) ) : 0 );
}
public function getSceneName(sceneNo:int):String
{
switch(sceneNo)
{
default:
return "Intro";
case 0:
return "Intro";
case 1:
return "MainMenu";
}
}
/* Main functions */
public function Main()
{
this.addEventListener('enterFrame',function() {
if(!this.startupRan)
realFrameNo += 1;
/* Main menu init */
if(getSceneNo() == 1 && !this.startupRan && currentFrame == 2)
{
stop();
this.startupRan = true;
/* Add keyboard events */
stage.addEventListener(KeyboardEvent.KEY_DOWN,function(event:KeyboardEvent){
var letter:String = String.fromCharCode(event.charCode).toUpperCase();
if(event.keyCode == 8)
updateMonitor("");
else if(event.keyCode == 13)
evalInput();
else if(isAlphabetic(letter))
updateMonitor(letter);
});
/* Add button events */
btnQ.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("Q"); });
btnW.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("W"); });
btnE.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("E"); });
btnR.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("R"); });
btnT.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("T"); });
btnY.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("Y"); });
btnU.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("U"); });
btnI.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("I"); });
btnO.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("O"); });
btnP.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("P"); });
btnA.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("A"); });
btnS.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("S"); });
btnD.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("D"); });
btnF.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("F"); });
btnG.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("G"); });
btnH.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("H"); });
btnJ.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("J"); });
btnK.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("K"); });
btnL.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("L"); });
btnZ.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("Z"); });
btnX.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("X"); });
btnC.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("C"); });
btnV.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("V"); });
btnB.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("B"); });
btnN.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("N"); });
btnM.addEventListener(MouseEvent.CLICK,function(){ updateMonitor("M"); });
btnDel.addEventListener(MouseEvent.CLICK,function(){ updateMonitor(""); });
btnEnter.addEventListener(MouseEvent.CLICK,function(){ evalInput(); });
btnReturn.addEventListener(MouseEvent.CLICK,function(){ evalInput(); });
}
});
}
public function updateMonitor(letter:String)
{
if(this.placeholderPresent) //Remove placeholder
lblInput.text = letter;
else if(letter == '' || letter == null) //Backspace
{
lblInput.text = lblInput.text.substr(0,lblInput.text.length-1);
}
else //Append text
lblInput.appendText(letter);
if(lblInput.text == "")
{
lblInput.text = "Type something to begin..";
this.placeholderPresent = true;
}
else
this.placeholderPresent = false;
}
public function evalInput():void
{
if(this.placeholderPresent) //Don't eval the starting text
return;
lblOutput.text = "Scanning for commands...";
for(var i:int = 0; i < this.commandList.length; i++)
{
if(lblInput.text.toLowerCase() == this.commandList[i][0])
{
this.commandList[i][1](this);
lblOutput.appendText("\nCommand ran.");
return;
}
}
lblOutput.appendText("\nNo command recognized.");
}
}
}
Full stack trace:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Main/evalInput()[H:\Year 2\Units\Unit 43 - Multimedia Design\Flash Application\Main.as:144]
at Function/<anonymous>()[H:\Year 2\Units\Unit 43 - Multimedia Design\Flash Application\Main.as:71]