I am using Mediafilepicker plugin to pick a video file from my device, but when I select the video it doesn't display on the app but once I press (pick a video) button for the second time its when the video shows
I searched for a similar problem but didn't find any
public pickvideo(){
let options: VideoPickerOptions = {
android: {
isCaptureMood: false,
isNeedCamera: true,
maxNumberFiles: 1,
isNeedFolderList: true,
maxDuration: 20,
},
};
let mediafilepicker = new Mediafilepicker();
mediafilepicker.openVideoPicker(options);
mediafilepicker.on("getFiles", res => {
let results = res.object.get('results');
this.videoSrc = results[0].file;
console.dir(results);
if (results) {
for (let i = 0; i < results.length; i++) {
let result = results[i];
console.dir(result);
let file = result.file;
console.log(file);
}
}
It doesn't show any errors
Use this code for pick a video from gallery and show in the app.
media-picker.component.ts:-
import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from "#angular/core";
import { Page } from "tns-core-modules/ui/page";
import * as app from 'tns-core-modules/application';
import { Mediafilepicker, VideoPickerOptions } from 'nativescript-mediafilepicker';
declare const AVCaptureSessionPreset1920x1080, AVCaptureSessionPresetHigh;
#Component({
selector: "media-picker",
moduleId: module.id,
templateUrl: "./media-picker.component.html",
styleUrls: ["./media-picker.component.scss"],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MideaPickerComponent implements OnInit {
public videoFileUrl: Array<string> = [];
constructor(public page: Page,
private ref: ChangeDetectorRef) {
// Use the constructor to inject services.
// Get reference to object we want to animate with code
}
ngOnInit(): void {
}
//Open video gallery list
public openVideoGallery() {
let allowedVideoQualities = [];
if (app.ios) {
allowedVideoQualities = [AVCaptureSessionPreset1920x1080, AVCaptureSessionPresetHigh];
}
let options: VideoPickerOptions = {
android: {
isCaptureMood: false,
isNeedCamera: true,
maxNumberFiles: 2,
isNeedFolderList: true,
maxDuration: 20,
},
ios: {
isCaptureMood: false
}
};
let mediafilepicker = new Mediafilepicker();
mediafilepicker.openVideoPicker(options);
mediafilepicker.on("getFiles", (res) => {
let results = res.object.get('results');
if (results) {
this.videoFileUrl = [];
for (let i = 0; i < results.length; i++) {
let result = results[i];
let file = result.file;
this.videoFileUrl.push(file);
if (result.file && app.ios && !options.ios.isCaptureMood) {
let fileName = file.replace(/^.*[\/]/, '');
setTimeout(() => {
mediafilepicker.copyPHVideoToAppDirectory(result.urlAsset, fileName).then(res => {
console.dir(res);
}).catch(e => {
console.dir(e);
});
}, 1000);
} else if (result.file && app.ios) {
// or we will get our own recorded video :)
console.log(file);
}
}
}
});
mediafilepicker.on("error", (res) => {
let msg = res.object.get('msg');
console.log(msg);
});
mediafilepicker.on("cancel", (res) => {
let msg = res.object.get('msg');
console.log(msg);
});
setInterval(() => {
// require view to be updated
this.ref.markForCheck();
}, 500);
}
}
media-picker.component.html:-
<StackLayout row="0">
<Button height="50" (tap)="openVideoGallery()" text="Open Video Gallery">
</Button>
</StackLayout>
<StackLayout row="1">
<VideoPlayer *ngFor="let video of videoFileUrl" src="{{video}}" autoplay="true" height="300"></VideoPlayer>
</StackLayout>
Related
When testing the API I have noticed that it is getting called around 6 times, there is no for/foreach loop that would make it run several times in the code so am unsure as to why this may be happening.
The API runs every time a user goes onto the Landing Screen.
Any advice would be appreciated
exports.getFilteredOpportunities = async (req, res) => {
let mongoQuery = generateMongoQuery(req);
try {
const opps = await Opportunity.find(mongoQuery)
.select(removeItems)
.sort({
createdAt: -1
});
res.status(200).json({
opportunities: opps,
});
} catch (error) {
res.status(500).json({
status: "error",
message: error,
});
}
};
GenerateMongoQuery function
const generateMongoQuery = (req) => {
let query = {};
// search param used searching through Title field, ie. search=food
if (req.query.search && req.query.search.length > 0) {
query.$or = [{}, {}];
query.$or[0].Title = query.$or[1].Description = new RegExp(
`${req.query.search}`,
"i"
);
}
// location param, i.e location=Glasgow,Manchester
if (req.query.location && req.query.location.length > 0) {
query.location = {
$in: req.query.location.split(",")
};
}
// timeslot param, i.e timeslot=Evening,Morning
if (req.query.timeslot && req.query.timeslot.length > 0) {
query.timeslot = {
$in: req.query.timeslot.split(",")
};
}
// category param, returning corresponding id i.e category=
if (req.query.category && req.query.category.length > 0) {
query.category = {
$in: req.query.category.split(",")
};
}
// Dont load expired opportunities
query.eventDate = {
$gte: new Date().toDateString()
};
// Only return non-cancelled opportunities
query.isCancelled = false;
return query;
};
The landing Screen
import { useState, useEffect } from "react";
import Opportunities from "../components/molecules/Opportunities";
import Filters from "../components/organisms/Filters";
import { IOpportunity } from "../Models/IOpportunity";
import OpportunitiesClient from "../Api/opportunitiesClient";
import Utils from "../Utils/Utils";
import FiltersClient from "../Api/filtersClient";
import { IFilters } from "../Models/IFilters";
import { ISelectedFilters } from "../Models/ISelectedFilters";
import Header from "../components/atoms/Header";
import Footer from "../components/atoms/Footer";
export default function LandingScreen(props) {
const [opportunities, setOpportunities] = useState<IOpportunity[]>([]);
const [filters, setFilters] = useState<IFilters[]>([]);
const [checkedFilters, setCheckedFilters] = useState<
ISelectedFilters | undefined
>({
Location: [],
Category: [],
Timeslot: [],
});
const [isLoading, setLoading] = useState<boolean>(true);
const [allResultsLoaded, setAllResultsLoaded] = useState<boolean>(false);
let pageToGet = 1;
const [scrollPosition, setScrollPosition] = useState(0);
const [totalOpps, setTotalOpps] = useState(0);
useEffect(() => {
getOpportunities();
getFilters();
}, []);
useEffect(() => {
setTotalOpps(opportunities.length);
}, [opportunities]);
const handleScroll = () => {
setScrollPosition(window.pageYOffset);
let scrollHeight = 0;
if ((props.scrollHeight === null) !== undefined) {
scrollHeight = +props.scrollHeight;
} else {
scrollHeight = document.scrollingElement.scrollHeight;
}
if (
window.innerHeight + document.documentElement.scrollTop >=
scrollHeight
) {
if (allResultsLoaded === false) {
setLoading(true);
}
setTimeout(() => {
pageToGet += 1;
getOpportunities();
}, 600);
}
window.removeEventListener("scroll", handleScroll);
};
window.addEventListener("scroll", handleScroll, { passive: true });
const setItemChecked = (filtername: string, filterType: string) => {
// reset page and results
pageToGet = 1;
setAllResultsLoaded(false);
setCheckedFilters(
Utils.setItemChecked(filtername, filterType, checkedFilters)
);
};
const resetFilters = () => {
// reset page and results
pageToGet = 1;
setAllResultsLoaded(false);
checkedFilters.Location = [];
checkedFilters.Category = [];
checkedFilters.Timeslot = [];
getOpportunities();
};
const getFilters = () => {
FiltersClient.getAll().then((filters) => {
setFilters(filters);
});
};
const getOpportunities = () => {
console.log(opportunities);
OpportunitiesClient.getWithParams(
Utils.getAxiosParams(checkedFilters)
).then((res) => {
definePage(res);
if (opportunities.length === res["opportunities"].length)
setAllResultsLoaded(true);
setLoading(false);
});
};
const definePage = (res) => {
if (pageToGet === 1) {
setOpportunities(res["opportunities"].slice(0, 15));
} else {
setOpportunities(
opportunities.concat(
res["opportunities"].slice(
opportunities.length,
opportunities.length + 15
)
)
);
}
};
return (
<div>
<Header page="landing" includePostButton={true} />
<div
data-testid="test-div1"
className="grid md:grid-cols-[150px_auto] sm:grid-cols-1 md:grid-flow-col gap-4 mx-4 mb-5 my-10"
>
<div></div>
<div className="card-container-title">
{totalOpps} Results{" "}
{checkedFilters.Location.length > 0 ? "(Filtered)" : ""}
</div>
</div>
<div
data-testid="test-div3"
className="grid md:grid-cols-[150px_auto] sm:grid-cols-1 md:grid-flow-col gap-4 mx-4"
>
<div>
<Filters
filters={filters}
getChecked={setItemChecked}
urlCall={getOpportunities}
resetFilters={resetFilters}
checkedFilters={checkedFilters}
/>
</div>
<div
data-testid="test-div4"
className={isLoading ? "opacity-50" : ""}
>
<div className="col-span-2">
<Opportunities
items={opportunities}
isLoading={isLoading}
allResultsLoaded={allResultsLoaded}
/>
</div>
</div>
</div>
<Footer />
</div>
);
}
I am trying to add markers on map, using a view and component
In view where i call an api and then i pass that data to component using v:bind but console.log in that component shows an empty array, when i make some changes in that component the page reloads and data is fetched following is my code in view and then component.
//Script for View
<script>
import Maps from '../components/Maps.vue';
import LoadingOverlay from '../components/loading.vue';
import MessageHelper from '../helpers/messageHelper';
import RepositoryFactory from '../repositories/RepositoryFactory';
const Catalogs = RepositoryFactory.get('catalogs');
export default {
components: {
Maps,
LoadingOverlay,
},
data() {
return {
zones_and_locations: [],
loadingConfig: {
isLoading: true,
cancellable: true,
onCancelMessage: this.onCancelMessage(),
isFullPage: true,
},
};
},
created() {
this.fetchPlacesData();
},
methods: {
async fetchPlacesData() {
const { data } = await Catalogs.getZoneLocations();
if (data.output === null) {
this.nullDataException();
} else {
const places = [];
data.output.forEach((value, index) => {
places.push(value);
});
this.zones_and_locations = places;
this.loadingConfig.isLoading = false;
}
},
onCancelMessage() {
return MessageHelper.getLoadingCancelMessage();
},
nullDataException() {
this.exceptionMessage = 'Data from API is not available.';
console.log(this.exceptionMessage);
},
},
};
</script>
//Script For Map.vue
<script>
import MarkerClusterer from '#google/markerclusterer';
import GoogleMapsHelper from '../helpers/GoogleMapsHelper';
export default {
name: 'GoogleMap',
props: ['zones_and_locations'],
data() {
return {
country: '',
markers: [],
map: '',
};
},
created() {
this.loadGoogleMaps();
},
methods: {
markerClusterer(map, markers) {
return new MarkerClusterer(
map,
markers,
{ imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m' },
);
},
async loadGoogleMaps() {
try {
const google = await GoogleMapsHelper();
const geoCoder = new google.maps.Geocoder();
const map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
mapTypeControl: false,
fullscreenControl: false,
});
geoCoder.geocode({ address: 'Singapore' }, (results, status) => {
if (status !== 'OK' || !results[0]) {
throw new Error(status);
}
// set Center of Map
map.setCenter(results[0].geometry.location);
map.fitBounds(results[0].geometry.viewport);
});
this.map = map;
let zones = [];
Array.prototype.forEach.call(this.zones_and_locations, child => {
var obj = {
lat: parseFloat(child.lat),
lng: parseFloat(child.lng),
}
var position = {
position: obj,
};
zones.push(position);
});
if (zones.length > 0) {
const markers = zones.map(x => new google.maps.Marker({ ...x, map }));
this.markerClusterer(map, markers);
}
} catch (error) {
console.error(error);
}
},
},
};
</script>
//Template for View
<template>
<div>
<!-- START::Loading Overlay -->
<LoadingOverlay
v-bind:loadingConfig="loadingConfig">
</LoadingOverlay><!-- END::Loading Overlay -->
<Maps v-bind:zones_and_locations="zones_and_locations"
></Maps>
</div>
</template>
//Template for Component
<template>
<div>
<div id="map" class="google-map"></div>
</div>
</template>
Data from the parent component are loaded asynchronously, so the created lifecycle hook inside the component is executed before the actual data comes, when they're still set as an empty array and are not reactive to change.
You can fix this by setting a watch inside the component, like this:
methods: {
...
},
watch: {
zones_and_locations (newVal, oldVal) {
this.loadGoogleMaps();
}
}
orelse you can set a reference to the child component and invoke its method when data comes:
<!-- main view -->
<Maps
v-bind:zones_and_locations="zones_and_locations"
ref="myMap"
></Maps>
async fetchPlacesData() {
const { data } = await Catalogs.getZoneLocations();
if (data.output === null) {
this.nullDataException();
} else {
const places = [];
data.output.forEach((value, index) => {
places.push(value);
});
this.zones_and_locations = places;
// using $refs
this.$refs.myMap.loadGoogleMaps();
this.loadingConfig.isLoading = false;
}
},
I am new in programming and I am trying to connect a Progress database using Progress Developer Studio authentication model (/WEB-INF/oeablSecurity-form-local.xml) with KENDO UI for Angular project. When I am using anonymous authentication everything is working fine, but I couldn't manage to make Form authentication with username and password. This is the code:
/// <reference path="progress/progress.d.ts" />
import { Component, ViewChild, Injectable } from '#angular/core';
import { Http } from '#angular/http';
import { Observable, BehaviorSubject } from 'rxjs/Rx';
import {
GridComponent,
GridDataResult,
DataStateChangeEvent,
// State
} from '#progress/kendo-angular-grid';
import {
State,
process
} from '#progress/kendo-data-query';
import * as Progress from "./progress/progress";
let progress = Progress.progress;
/* Example service */
#Injectable()
export class CategoriesService extends BehaviorSubject<GridDataResult> {
private tableName: string = 'Client';
private jsdoPromise: Promise<Progress.progress.data.JSDO>;
constructor(private http: Http) {
super(null);
const serviceURI = 'serviceURI';
const catalogURI = 'catalogURI';
let opts: Progress.progress.data.JSDOSessionOptions = {
serviceURI: serviceURI,
};
let session = new progress.data.JSDOSession(opts);
this.jsdoPromise = new Promise( (resolve, reject) => {
session.login("", "").done(function (session: Progress.progress.data.JSDOSession, result: any, info: any) {
console.log("session.login");
session.addCatalog(catalogURI).then(() => {
resolve(new progress.data.JSDO('AdvClients'));
});
})
})
}
public query(state: any): void {
this.fetch(this.tableName, state)
.subscribe(x => super.next(x));
}
private fetch(tableName: string, state: State): Observable<GridDataResult> {
let that = this;
let query = {
skip: state.skip,
top: state.take
};
let promise = new Promise((resolve, reject) => {
this.jsdoPromise.then((jsdo) => {
console.log("jsdoPromise.resolve");
let afterFill = (jsdo: any, success: any, request: any) => {
jsdo.unsubscribe('AfterFill', afterFill, this);
if (success) {
let data = jsdo.getData();
if (query.top) {
let afterInvoke = (jsdo1: any, success1: any, request1: any): void => {
jsdo.unsubscribe('AfterInvoke', 'count', afterInvoke, this);
console.log("promise.resolve 1");
resolve(<GridDataResult>{
data: data,
total: request1.response.numRecs
});
};
jsdo.subscribe('AfterInvoke', 'count', afterInvoke, this);
jsdo.count(query);
} else {
console.log("promise.resolve 2");
resolve(<GridDataResult>{
data: data,
total: data.length
});
}
} else {
reject(new Error('Error while executing query'));
}
};
jsdo.subscribe('AfterFill', afterFill, this);
jsdo.fill(query);
})
});
let result = Observable.fromPromise(promise)
.map((ret: GridDataResult) => (<GridDataResult>{
data: ret.data,
total: ret.total
}));
return result;
}
}
I made it.
const serviceURI = 'http://ctc-server:8810/CtcIdea';
const catalogURI = serviceURI + '/static/CtcIdeaService1.json';
const authenticationModel = progress.data.Session.AUTH_TYPE_FORM;
let opts: Progress.progress.data.JSDOSessionOptions = {
serviceURI: serviceURI,
authenticationModel: authenticationModel
};
i am new in react native,i try to developing native application in react native but i have onPress click event issue.
InfoSwipper.js file i was click on Sign In button display "undefined is not an object(evaluating 'this.props.navigator.push') ". I am not sure what I am missing. please some one help me.
Thank you in advance.
index.android.js file code
"use strict";
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
StatusBar,
AsyncStorage,
} from 'react-native';
var SignUp = require("./components/SignUp");
var InfoScreens = require("./components/InfoScreens");
import SplashScreen from 'react-native-splash-screen'
var Kahaani = React.createClass({
_renderScene(route, navigator) {
if (route.id === 0) {
return <InfoScreens navigator={navigator} />
}
else if (route.id === 1) {
StatusBar.setHidden(false);
console.log('WRONG SIGNIN', "here");
return <LogIn navigator={navigator} />
}
},
componentDidMount() {
// do anything while splash screen keeps, use await to wait for an async task.
SplashScreen.hide();
},
render: function() {
return (
<Navigator
style={styles.navigationContainer}
initialRoute={{id: 0, }}
renderScene={this._renderScene} />
);
}
});
var styles = StyleSheet.create({
navigationContainer: {
flex: 1,
},
});
AppRegistry.registerComponent('Kahaani', () => Kahaani);
swipperScreen.js
'use strict';
import React, { Component } from 'react';
import {
Dimensions, // Detects screen dimensions
Platform, // Detects platform running the app
ScrollView, // Handles navigation between screens
StyleSheet, // CSS-like styles
View,
Text,Navigator, TouchableHighlight, // Container component
} from 'react-native';
import LogIn from './LogIn';
var navigator;
class InfoScreenSwiper extends Component {
constructor(props)
{
super(props);
}
static defaultProps = {
horizontal: true,
pagingEnabled: true,
showsHorizontalScrollIndicator: false,
showsVerticalScrollIndicator: false,
bounces: false,
scrollsToTop: false,
removeClippedSubviews: true,
automaticallyAdjustContentInsets: false,
index: 0
};
state = this.initState(this.props);
initState(props) {
const total = props.children ? props.children.length || 1 : 0,
index = total > 1 ? Math.min(props.index, total - 1) : 0,
offset = width * index;
const state = {
total,
index,
offset,
width,
height,
};
this.internals = {
isScrolling: false,
offset
};
return state;
}
onScrollBegin = e => {
// Update internal isScrolling state
this.internals.isScrolling = true;
}
onScrollEnd = e => {
// Update internal isScrolling state
this.internals.isScrolling = false;
// Update index
this.updateIndex(e.nativeEvent.contentOffset
? e.nativeEvent.contentOffset.x
// When scrolled with .scrollTo() on Android there is no contentOffset
: e.nativeEvent.position * this.state.width
);
}
onScrollEndDrag = e => {
const { contentOffset: { x: newOffset } } = e.nativeEvent,
{ children } = this.props,
{ index } = this.state,
{ offset } = this.internals;
if (offset === newOffset &&
(index === 0 || index === children.length - 1)) {
this.internals.isScrolling = false;
}
}
updateIndex = (offset) => {
const state = this.state,
diff = offset - this.internals.offset,
step = state.width;
let index = state.index;
if (!diff) {
return;
}
index = parseInt(index + Math.round(diff / step), 10);
this.internals.offset = offset;
this.setState({
index
});
}
swipe = () => {
if (this.internals.isScrolling || this.state.total < 2) {
return;
}
const state = this.state,
diff = this.state.index + 1,
x = diff * state.width,
y = 0;
this.scrollView && this.scrollView.scrollTo({ x, y, animated: true });
this.internals.isScrolling = true;
if (Platform.OS === 'android') {
setImmediate(() => {
this.onScrollEnd({
nativeEvent: {
position: diff
}
});
});
}
}
renderScrollView = pages => {
return (
<ScrollView ref={component => { this.scrollView = component; }}
{...this.props}
contentContainerStyle={[styles.wrapper, this.props.style]}
onScrollBeginDrag={this.onScrollBegin}
onMomentumScrollEnd={this.onScrollEnd}
onScrollEndDrag={this.onScrollEndDrag}
>
{pages.map((page, i) =>
// Render each slide inside a View
<View style={[styles.fullScreen, styles.slide]} key={i}>
{page}
</View>
)}
</ScrollView>
);
}
renderPagination = () => {
if (this.state.total <= 1) {
return null;
}
const ActiveDot = <View style={[styles.dot, styles.activeDot]} />,
Dot = <View style={styles.dot} />;
let dots = [];
for (let key = 0; key < this.state.total; key++) {
dots.push(key === this.state.index
// Active dot
? React.cloneElement(ActiveDot, { key })
// Other dots
: React.cloneElement(Dot, { key })
);
}
return (
<View
pointerEvents="none"
style={[styles.pagination, styles.fullScreen]}>
{dots}
</View>
);
}
onMainPressLogIn= () =>
{
console.log('WRONG SIGNIN', "onMainPressLogIn");
this.props.navigator.push({
id:1
});
}
onSubmitPressed () {
console.log('WRONG SIGNIN', "onSubmitPressed");
this.props.navigator.push({
id:2
})
}
renderButtonBottom = () => {
const lastScreen = this.state.index === this.state.total - 1;
return (
<View pointerEvents="box-none" style={[styles.buttonWrapper]}>
<View style={ [styles.viewButton]}>
<Text style={[styles.buttonLogIn,styles.buttonAll]} onPress={this.onMainPressLogIn} >LOG IN</Text>
<Text style={[styles.buttonSignUp,styles.buttonAll]} onPress={(this.onSubmitPressed.bind(this))}>SIGN UP</Text>
</View>
</View>
);
}
render = ({ children } = this.props) => {
return (
<View style={[styles.container, styles.fullScreen]}>
{/* Render screens */}
{this.renderScrollView(children)}
{/* Render pagination */}
{this.renderPagination()}
{/* Render Continue or Done button */}
{this.renderButtonBottom()}
</View>
);
}
}
module.exports = InfoScreenSwiper;
I'm trying to record audio via the microphone in the browser and then save it to file server side using Node and a binary server. I am using this tutorial as a guide but am having trouble getting it to work with Angular2. Currently it appears to be saving some type of file to the server but it's not any type of playable audio. Here's all my code:
import { Component } from '#angular/core';
import { ContributorService } from './contributor.service';
import { CardDetailService } from './card-detail.service';
import { CardDetailComponent } from './card-detail.component';
import { Router, ActivatedRoute, Params } from '#angular/router';
import { Location } from '#angular/common';
declare let navigator: any;
declare let MediaRecorder: any;
declare let BinaryClient: any;
#Component({
selector: 'contributor',
template: `
<h1>Record Message</h1>
<button (click)='start()'>Start</button>
<button (click)='stop()'>Stop</button>
<button (click)='play()'>Play</button>
<a>{{hf}}</a>
<button class="go-back" (click)="goBack()">Done</button>
`
})
export class ContributorComponent {
private chunks: any[] = [];
private recorder;
private audio;
private counter = 1;
private Stream;
private recording = false;
constructor(
private contributorService: ContributorService,
private cardDetailService: CardDetailService,
private location: Location,
private route: ActivatedRoute,
private router: Router,
) {}
ngOnInit() {
let client = new BinaryClient('ws://localhost:9001');
client.on('open', function() {
let Stream = client.createStream();
});
let audio = {
tag: 'audio',
type: 'audio/ogg',
ext: '.ogg',
gUM: {audio: true}
};
let context = new AudioContext();
if (!navigator.getUserMedia) {
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia || navigator.msGetUserMedia;
}
if (navigator.getUserMedia) {
navigator.getUserMedia({audio: true }, this.success, function(e) {
alert('Error capturing audio.');
});
} else {
alert('getUserMedia not supported in this browser.');
}
}
start() {
this.recording = true;
}
stop() {
this.recording = false;
this.Stream.end();
}
recorderProcess(e) {
let left = e.inputBuffer.getChannelData(0);
this.Stream.write(this.convertFloat32ToInt16(left));
}
success(e) {
let context = new AudioContext();
// the sample rate is in context.sampleRate
let audioInput = context.createMediaStreamSource(e);
let recorder = context.createScriptProcessor(2048, 1, 1);
this.recorder.onaudioprocess = function(e){
if (!this.recording) { return; };
console.log ('recording');
var left = e.inputBuffer.getChannelData(0);
this.Stream.write(this.convertoFloat32ToInt16(left));
};
audioInput.connect(this.recorder);
this.recorder.connect(context.destination);
}
convertFloat32ToInt16(buffer) {
let l = buffer.length;
let buf = new Int16Array(l);
while (l--) {
buf[l] = Math.min(1, buffer[l]) * 0x7FFF;
}
return buf.buffer;
}
goBack() {
this.location.back();
}
}
and here are the errors it throws:
contributor.component.ts:96Uncaught TypeError: Cannot read property 'recorder' of undefined(…)ContributorComponent.success # contributor.component.ts:96
core.umd.js:3004 EXCEPTION: Error in ./ContributorComponent class ContributorComponent - inline template:4:10 caused by: Cannot read property 'end' of undefinedErrorHandler.handleError