Load a new video by id into a Brightcove Player loaded via Brightcove Player Loader - brightcove

I have loaded a Brightcove video player on my page with Brightcove Player Loader:
brightcovePlayerLoader({
refNode: document.querySelector('#mainvid'),
accountId: myaccountId, //this is a variable with global scope
playerId: '947WeZ6d',
videoId: mainvidID
})
.then(function(success) {
myPlayer = success.ref;
console.log('success', success);
myPlayer.on('loadedmetadata',function(){
//myPlayer.muted(true);
//myPlayer.play();
});
})
.catch(function(error) {
console.log('error', error);
});
When the user clicks an image, I want to read the ID of the image and use that as a new VideoID for myPlayer. But how would I do that?
$('.vid-thumbnail').on('click', function() {
myPlayer.videoId = maidvidID; //doesn't work
});

Use the regular player catalog methods with the player returned in success.
myPlayer.catalog.getVideo('12345', function(error, video){
myPlayer.catalog.load(video);
});

Related

caching a dynamic view PWA ASP

I have a question about caching in PWA.
I would like to let user choose a list to cache. For example:
User creating few lists, and then he choose one, to save for offline.
When he is offline he can only open 2 views:
smth like "u are offline, do you want to open saved list?" (if it exist)
View with saved list.
At this moment, I am caching all views that user visited, but can't cache views with dynamic data.
I'm using PWA.essentials to do PWA.
services.AddProgressiveWebApp(new PwaOptions
{
RegisterServiceWorker = true,
RegisterWebmanifest = false,
Strategy = ServiceWorkerStrategy.NetworkFirst,
RoutesToPreCache = "/, /Home/Offline, /Home/Saved_list",
OfflineRoute="Offline.html"
});
I have created manifest.json. When im using dev mode in chrome, I can see that at this moment, I'm caching all views execpt views with more complicated path (like /Controller/View/something).
I'm saving list, that user choose in a "Offline.json" file, that is cached too,but when user changes list to save, file "offline.json" is still no updated. I mean my PWA doesn't replace it with new one.
So I have a question about how can I save dynamic list to browser cache, and then set offline route to it.
Service Worker Created by pwa.essentials:
(function () {
'use strict';
// Update 'version' if you need to refresh the cache
var version = 'v1.0::NetworkFirst';
var offlineUrl = "Offline.html";
// Store core files in a cache (including a page to display when offline)
function updateStaticCache() {
return caches.open(version)
.then(function (cache) {
return cache.addAll([
offlineUrl,
'/','/Home','/Generate/Select_mode'
]);
});
}
function addToCache(request, response) {
if (!response.ok)
return;
var copy = response.clone();
caches.open(version)
.then(function (cache) {
cache.put(request, copy);
});
}
self.addEventListener('install', function (event) {
event.waitUntil(updateStaticCache());
});
self.addEventListener('activate', function (event) {
event.waitUntil(
caches.keys()
.then(function (keys) {
// Remove caches whose name is no longer valid
return Promise.all(keys
.filter(function (key) {
return key.indexOf(version) !== 0;
})
.map(function (key) {
return caches.delete(key);
})
);
})
);
});
self.addEventListener('fetch', function (event) {
var request = event.request;
// Always fetch non-GET requests from the network
if (request.method !== 'GET') {
event.respondWith(
fetch(request)
.catch(function () {
return caches.match(offlineUrl);
})
);
return;
}
event.respondWith(
fetch(request)
.then(function (response) {
// Stash a copy of this page in the cache
addToCache(request, response);
return response;
})
.catch(function () {
return caches.match(request)
.then(function (response) {
return response || caches.match(offlineUrl);
})
.catch(function () {
if (request.headers.get('Accept').indexOf('image') !== -1) {
return new Response('<svg role="img" aria-labelledby="offline-title" viewBox="0 0 400 300" xmlns="http://www.w3.org/2000/svg"><title id="offline-title">Offline</title><g fill="none" fill-rule="evenodd"><path fill="#D8D8D8" d="M0 0h400v300H0z"/><text fill="#9B9B9B" font-family="Helvetica Neue,Arial,Helvetica,sans-serif" font-size="72" font-weight="bold"><tspan x="93" y="172">offline</tspan></text></g></svg>', { headers: { 'Content-Type': 'image/svg+xml' } });
}
});
})
);
});
})();
You are saving the user selected pages’ list at server side in offline.json and you are caching that file too. As per working of PWA cached resources are served from cache and not from server until cache is removed/cleared.
You can take 2 approach.
Whenever user adds to the offline.json you need enforce service worker to update the offline file.
You can simply store the user selecting in local storage and from there you add pages to cache list.

How to stop video playing in background Nativescript -angular

Im using video in my project ,but video is playing in background ,When i move to another component.This problem occurs only in ios ,not in android
Html
<VideoPlayer
src="{{videoUrl}}"
height="300"></VideoPlayer>
angular
index:any
videoUrl :any
ngOnInit() {
this.router.paramMap.subscribe(
(response) =>{
this.index = response.get('id')
this.videoUrl=this.galleryService.getVideoById(this.index)
console.log(response)
}
)
}
This is my code .
Listen to navigatingFrom event on your current Page and call pause() method on the VideoPlayer.
HTML
<VideoPlayer #player
src="{{videoUrl}}"
height="300"></VideoPlayer>
TS
#ViewChild("player") player: ElementRef;
constructor(private page: Page) { }
ngOnInit() {
this.router.paramMap.subscribe(
(response) => {
this.index = response.get('id')
this.videoUrl=this.galleryService.getVideoById(this.index)
console.log(response)
});
this.page.on(Page.navigatingFromEvent, () => {
this.player.nativeElement.pause();
});
}
ngOnDestroy() {
this.page.off(Page.navigatingFromEvent);
}
You may also use Router Events on Angular, but you might have to filter the appropriate route.

Nativescript imagepicker .getImage() is not a function error

I have been trying to implement the answer to this question but keep getting the error "selected.getImage is not a function".
I have tried multiple different code examples at this point and I'm stumped. It seems like this is a type error, but I'm not sure where I can correct this.
I am looking to select a single image and return the path to that image in order to upload to the server. I don't need to display it on the device, though that is an option I suppose. Seems easy enough, but apparently I'm missing something.
I'm using v. 6.0.1 or the imagepicker plugin. I'd quote the code, but at this point I am using the exact example provided by Shiva Prasad in the above question.
Adding code per Max Vollmer:
var context = imagepickerModule.create({
mode: "single" // allow choosing single image
});
context
.authorize()
.then(function () {
return context.present();
})
.then(function (selection) {
console.log("Selection done:");
setTimeout(() => {
selection.forEach(function (selected) {
selected.getImage().then((source) => {
console.log(selected.fileUri); // this is the uri you need
});
});
}, 1000);
}).catch(function (e) {
console.log(e);
});
I was facing the exact same error yesterday.
I use the fromAsset function directly on the "selected" because apparently with the new version of this plugin, "selected" is an Asset. So you got an imageSource and you can use the "saveToFile" function that will copy the Asset into a new location (get this location using fileSystemModule from TNS). Use the path of this new location for your UI, and the image will appear. You can also create a file object from this location fileSystemModule.File.fromPath(path);, I use for upload.
context
.authorize()
.then(function () {
return context.present();
})
.then(function (selection) {
selection.forEach(function (selected) {
let file;
if (selected._android) {
file = fileSystemModule.File.fromPath(selected._android);
//viewModel.uploadFile(file);
}else{
imageSourceModule.fromAsset(selected).then((imageSource) => {
const folder = fileSystemModule.knownFolders.documents().path;
const fileName = "Photo.png";
const path = fileSystemModule.path.join(folder, fileName);
const saved = imageSource.saveToFile(path, "png");
if (saved) {
console.log("Image saved successfully!");
file = fileSystemModule.File.fromPath(path);
//viewModel.uploadFile(file);
}else{
console.log("Error! - image couldnt save.");
}
});
}
});
}).catch(function (e) {
console.log(e);
// process error
});
Explanation
The uncommented snippet (//viewModel.uploadFile(file);), viewModel reference (will be different on your app) and the function: uploadFile for example is where you would pass the file to upload it or set it to the image.src etc
Make sure to declare imageSourceModule at the top.
const imageSourceModule = require("tns-core-modules/image-source");

How can I do a simple AJAX call to play audio via React / Redux?

I am trying to auto play some audio, and on iOS, it won't autoplay. However, if I wrap it in an AJAX call, it'll fire. So here's what I have:
// run on page load
var audio = document.getElementById('audio');
jQuery.ajax({
url: 'ajax.js',
async: false,
success: function() {
audio.play(); // audio will play in iOS before 4.2.1
}
});
How would I set this up with React / Redux?
Here's a very simple example using fetch (which is supported by most browsers out of the box) and blob object URLs. You could of course also use jQuery's ajax.
It's very similar to your code, but inside the componentDidMount method. The audio element is referenced via React's refs.
class Player extends React.Component {
componentDidMount() {
fetch(this.props.src)
.then(res => res.blob())
.then(blob => {
const { audio } = this.refs;
audio.src = URL.createObjectURL(blob);
audio.play();
});
}
render() {
return <audio ref="audio" controls></audio>;
}
}
ReactDOM.render(
<Player src="https://ia802508.us.archive.org/5/items/testmp3testfile/mpthreetest.mp3" />,
document.getElementById("View")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='View'></div>
🔊❗️
Also, it is usually not recommended to use refs in React, but since we need access to the actual DOM node of the audio player it is a necessary evil.

jplayer+Ajax inserted content

I am using jPlayer to play audio files.
If I use the player on content, which is privided, when the page gets loaded, it works without any problems.
I also need it for HTML which is inserted by AJAX. Here it does not work. It seems, that the ready event is not triggered.
I wrote a function, which can be executed by click(). In that way, I can click it manually, when the HTML which contains the player is fully loaded. Here I have the same problem: The ready event is not triggered.
This is my function which works on non ajax inserted players fine:
$('.jp-jplayer').each(function () {
var src = $(this).attr('data-src');
var id = $(this).attr('id');
var post_id = $(this).attr('data-id');
alert('beg');
$('#' + id).jPlayer({
ready: function () {
$(this).jPlayer('setMedia', {
mp3: "/prelisten/_lofidl/change_of_heart_full_lofi.mp3",
});
alert('#' + id);
},
swfPath: "/wp-content/themes/Dark_3Chemical_DE_mit_Pagenavi/Dark_3Chemical_DE/audioplayer/js",
//////ERRRROOOOOR
solution: "flash, html",
supplied: "mp3",
wmode: "window",
cssSelectorAncestor: "#jp_container_" + post_id,
play: function () { // To avoid both jPlayers playing together.
$(this).jPlayer("pauseOthers");
},
repeat: function (event) { // Override the default jPlayer repeat event handler
if(event.jPlayer.options.loop) {
$(this).unbind(".jPlayerRepeat").unbind(".jPlayerNext");
$(this).bind($.jPlayer.event.ended + ".jPlayer.jPlayerRepeat", function () {
$(this).jPlayer("play");
debug($(this));
});
} else {
$(this).unbind(".jPlayerRepeat").unbind(".jPlayerNext");
$(this).bind($.jPlayer.event.ended + ".jPlayer.jPlayerNext", function () {
//$("#jquery_jplayer_4858").jPlayer("play", 0);
});
}
},
});
$("#jplayer_inspector").jPlayerInspector({
jPlayer: $('#' + id)
});
});
Currently I am setting the src manually to exclude any possible errors here.
How can I get this function running on AJAX inserted content?
EDIT:
This is the code, which fetches the html including the players:
$.get('/query_posts.php', {
paged: _page,
cats: cols
}, function(data) {
$('#search-results').append(data).fadeIn(300);
//create_player_scripts();
//set_players();
$('#search-results').find('input[name="cartLink"]').each(function() {
$(this).val($(this).closest('.post1').find('.post_headl a').attr('href'));
});
});
To make an AJAX page reload work I had to first destroy all jplayer instances. So I wrote a little function that grabs all instances of a jplayer on the site (by looking for jp-audio classes) and calls jplayer('destroy'); and jplayer('clearMedia'). This function gets called in the $.ajax({ beforeSend: destroyJplayerInstances(); })
UPDATE:
Here is a statement from the developer of jPlayer, Mark Panaghiston:
https://groups.google.com/forum/#!topic/jplayer/Q_aRhiyYvQo
Hope that helps!

Resources