Similar to this question asking about how to play YouTube videos on tvOS, I'd like to play Vimeo videos in the app I'm building. However, as explained here, regular web views (which is how I do things in iOS) are out.
How would I go about playing a Vimeo video on tvOS assuming I knew the URL to the video page but not the URL to the raw .mp4 file?
Well, apparently, there is no way to play a Vimeo video in a WebView, because tvOS SDK doesn't have a WebView.
The only option we have is AVPlayer, but it requires a direct URL to a video, and Vimeo won't give us direct video URLs for free.
Right now, the only possible way is to purchase Vimeo's PRO membership ($199 per year at the moment) and retrieve direct video URLs via Vimeo's API.
EDIT: as nickv2002 noted, this approach will give you direct URLs only to YOUR OWN videos. Thi means, that even with Vimeo PRO you can't just take any video on Vimeo and get a direct URL for it.
Using this pod, tvOS can play vimeo contents,
Install
pod 'YTVimeoExtractor'
and
import YTVimeoExtractor
And use this function to play the video
func playVimeoVideo(videoId: String)
{
YTVimeoExtractor.shared().fetchVideo(withVimeoURL: "https://vimeo.com/video/\(videoId)", withReferer: nil) { (video:YTVimeoVideo?, error:Error?) in
if let streamUrls = video?.streamURLs
{
var streamURL: String?
var streams : [String:String] = [:]
for (key,value) in streamUrls {
streams["\(key)"] = "\(value)"
print("\(key) || \(value)")
}
if let large = streams["720"]
{
streamURL = large
}
else if let high = streams["480"]
{
streamURL = high
}
else if let medium = streams["360"]
{
streamURL = medium
}
else if let low = streams["270"]
{
streamURL = low
}
if let url = streamURL
{
let videoURL = NSURL(string: url)
let player = AVPlayer(url: videoURL! as URL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
playerViewController.player!.play()
}
}
}
}
}
You can play your video using AVPlayer, just like on iOS.
AVPlayer Documentation
Related
I am using getUserMedia and mediaRecorder API to record an video from webcam.
I am using chrome version 80.
How to getUserMedia and record the video mixing the mp3 with javascript? mp3 can play pause and stop
I don't know how to mixing the mp3 to the video stream on live.
When I removeTrack and addTrack, I stop on MediaRecorder fail.
show Error: Failed to execute 'stop' on 'MediaRecorder': The MediaRecorder's state is 'inactive'.
my code on codepen: https://codepen.io/zhishaofei3/pen/eYNrYGj
and prime codes:
function getFileBuffer(filepath) {
return fetch(filepath, {method: 'GET'}).then(response => response.arrayBuffer())
}
function mp3play() {
getFileBuffer('song.mp3')
.then(buffer => context.decodeAudioData(buffer))
.then(buffer => {
console.log(buffer)
const source = context.createBufferSource()
source.buffer = buffer
let volume = context.createGain()
volume.gain.value = 1
source.connect(volume)
dest = context.createMediaStreamDestination()
volume.connect(dest)
// volume.connect(context.destination)
source.start(0)
const _audioTrack = stream.getAudioTracks();
if (_audioTrack.length > 0) {
_audioTrack[0].stop();
stream.removeTrack(_audioTrack[0]);
}
console.log(dest.stream)
console.log(dest.stream.getAudioTracks()[0])
stream.addTrack(dest.stream.getAudioTracks()[0])
})
}
thank you !
Many containers don't support adding/removing tracks like that, and it's doubtful the Media Recorder API does at all. It's an unusual thing to do.
You need to create the stream you're going to record before instantiating Media Recorder, with all of the tracks you want. Therefore, you need to do things in this order:
Set up your AudioContext.
Call getUserMedia(). (And while you're at it, set audio: false in your constraints. No need to open a microphone if you're not using one.)
videoStream.getVideoTracks() and dest.stream.getAudioTracks() to get all of the tracks.
Create a new MediaStream with those tracks. new MediaStream([audioTrack, videoTrack])
Now, run your MediaRecorder on this new MediaStream and you'll have what you want.
I am using html content for uiwebview in swift but going to one view controller to another controller navigate suddenly moving inner video image.i tried to clear web view- refer link How To Clear A UIWebView and
also used autoresizing autoresizingMask = .flexibleWidth but didn't solved.Clear web view cache using in viewDiddisappear cann't get solution[
Swift 3.0 code:
let htmlString:String = descriptionHtml
webView.loadHTMLString(htmlString, baseURL: nil)
webView.scrollView.isScrollEnabled = false
webView.allowsInlineMediaPlayback = true
let aStr = String(format: "%#%x", "document.querySelector('meta[name=viewport]').setAttribute('content', 'width=%d;', false); ", webView.frame.size.width)
webView.stringByEvaluatingJavaScript(from: aStr)
webView.delegate = self
I would appreciate if someone could help.
Simple question...
I am making a small webpage that should be viewed from a SmartTV. This page serves some Ajax calls etc.
But the site also shows a Youtube video. The problem is that Youtube video shows up as Flash content. The smart TV doesn't play flash, so I'm in trouble.
Anyone have any idea how to handle this?
Yes, I wanted to do the exact same thing. This is how implemented this logic. And it is working fine for me.
HTML:
<div id="webElement" style="display: none;"></div>
JS:
When ajax call is received (contains many files of type YouTube/WebPages/MP4 files):
if (Utility.isYouTube(dr.FileName)) {
dr.IsWeb = true;
dr.WebUrl = "http://www.youtube.com/embed/" + Utility.getParameterByName('v', dr.FileName) + "?rel=0&autoplay=1";
}
This is how I played it (if webpage/Youtube):
var webElement = jQuery("#webElement");
webElement.empty();
var obj = "<object type='text/html' width='1920' height='1080' data='" + dr.WebUrl + "' onerror='Player.onWebElementError();'> </object>";
webElement.append(obj);
webElement.show();
Hope it will help you to achieve what you want.
Samsung SmartTVs do use Flash. It depends on which TV you want your app to run. If you are developing for 2011 it will be a no go, since 2011 SmartTV models only support AS2.0 and YouTube has stopped supporting AS2.0 for their API.
For 2012 and 2013 models you can easily embed a YouTube video by doing:
var attributes = { id: "myytplayer" }, params = { allowScriptAccess: "always", allowFullScreen: "true"};
swfobject.embedSWF('http://www.youtube.com/apiplayer?enablejsapi=1&version=2&fs=1', "ytplayer",400, 600, "6", null, null, params, attributes);
Then to load a video:
ytp.getVideo('http://www.youtube.com/watch?v=ubAjEjkJIJo');
ytp.getVideo = function (url) {
//loads video by url
ytp.ytp_ref.cueVideoByUrl(url);
};
I'm pretty new to the HTML5 audio api: I've read some of the related articles at HTML5 Rocks, but it can be a little tricky flipping between Javascript and Dart at times.
In any case, I've been experimenting with HTML5 Audio in Dart. To produce sound effects for a simple game, I created a class as follows. I created an AudioContext, loaded sound data into SoundBuffers, and when the sound needed to be played, created an AudioBufferSourceNode via which to play the data stored in the buffers:
class Sfx {
AudioContext audioContext;
List<Map> soundList;
int soundFiles;
Sfx() {
audioContext = new AudioContext();
soundList = new List<Map>();
var soundsToLoad = [
{"name": "MISSILE", "url": "SFX/missile.wav"},
{"name": "EXPLOSION", "url": "SFX/explosion.wav"}
];
soundFiles = soundsToLoad.length;
for (Map sound in soundsToLoad) {
initSound(sound);
}
}
bool allSoundsLoaded() => (soundFiles == 0);
void initSound(Map soundMap) {
HttpRequest req = new HttpRequest();
req.open('GET', soundMap["url"], true);
req.responseType = 'arraybuffer';
req.on.load.add((Event e) {
audioContext.decodeAudioData(
req.response,
(var buffer) {
// successful decode
print("...${soundMap["name"]} loaded...");
soundList.add({"name": soundMap["name"], "buffer": buffer});
soundFiles--;
},
(var error) {
print("error loading ${soundMap["name"]}");
}
);
});
req.send();
}
void sfx(AudioBuffer buffer) {
AudioBufferSourceNode source = audioContext.createBufferSource();
source.connect(audioContext.destination, 0, 0);
source.buffer = buffer;
source.start(0);
}
void playSound(String sound) {
for (Map m in soundList) {
print(m);
if (m["name"] == sound) {
sfx(m["buffer"]);
break;
}
}
}
}
(The sound effects are in a folder "SFX". Now that I look at the code, there are probably a million better ways to organise the data, but that's besides the point right now.) I am able to play sound effects by creating an instance of Sfx and calling the method playSound.
e.g.
#import('dart:html');
#source('sfx.dart');
Sfx sfx;
void main() {
sfx = new Sfx();
window.on.keyUp.add((KeyboardEvent keX) {
sfx.playSound("MISSILE");
});
}
(Edit: added code to play sound when a key is hit.)
The problem is: although with the dart2js Javascript, the sound effects play as expected in Safari, when they are played in Dartium or (with the dart2js Javascript) in Chrome, they are distorted. (In Firefox, there are even worse problems!)
Is there anything obvious that I have neglected to do or that I need to take into account? Otherwise, are there any references or tutorials, preferably in a Dart context, that might help?
thanks for trying Dart!
First off, Firefox doesn't support Web Audio API (yet?) Chrome and Safari support Web Audio API. You can track adoption of Web Audio API here: http://caniuse.com/#feat=audio-api
Second, please try this Web Audio API sample in Dartium: https://github.com/dart-lang/dart-html5-samples/tree/master/web/webaudio/intro You will need to clone the repo first and run it locally. This sample works for me locally.
This sounds more like a bug report. If the sample from dart-html5-samples works for you, but your above code continues to be distorted, please open a bug at http://dartbug.com/new so we can take a look.
One thing to consider is waiting until the specific MISSLE sound is loaded before hooking up the keyUp handler.
I'm hoping to get pointed in the right direction here. The problem I'm having is trying to figure out how to read an HTML created cookie in Flash. I have a video player that should autoplay once in a 24hour period, the next day it should autoplay again for the end-user.
This is what the script on the HTML page looks like that displays the Flash player and the cookie:
<script type="text/javascript">
var so = new SWFObject("flvplayer.swf", "mymovie", "640", "394", "8", "#90ab69");
var x = readCookie('homepageIntro') // <- The Cookie (How do I read this in Flash?)
so.addParam("quality", "high");
so.addParam("wmode", "transparent");
so.useExpressInstall('expressinstall.swf');
so.addVariable("autostart", "false");
so.addVariable("file", "video.flv");
so.addVariable("key", "");
so.addVariable("showfsbutton", "false");
so.addVariable("noControls", "false");
so.addVariable("home", "true");
so.write("flashcontent");
</script>
Not knowing how to read that var x inside of Flash, I tried to get around having to use it by using a Flash cookie, however now the video player will only ever autoplay once and never ever autoplay again(unable to clear the Flash cookie).
public function sharedObjectCheck():void
{
if (mySharedObject.data.flashCookie == "true"){
//Code to NOT autoplay video
} else if (mySharedObject.data.flashCookie == null){
mySharedObject.data.flashCookie = "true"; //if first time, set the cookie value
mySharedObject.flush(); //add the cookie
}
}
I did some searching and found this Have a HTML page play Flash movie only once (not when revisited…) but again this is just a Flash function which never allows for a restart in a certain time period.
So my question to my fellow Flash stackers is how do I read that var x(cookie) in Flash?
A direct answer to your question is to use ExternalInterface
import flash.external.*
try {
var cookie : String = ExternalInterface.call("readCookie", "homepageIntro") as String;
} catch (error : SecurityError) {
trace("SecurityError:", e.message);
} catch (error : Error) {
trace("Error:", e.message);
}
You likely also need to set allowScriptAccess to let the call run.
Using a LSO is probably your best option, or passing in the value of x as a FlashVar.
Have you tried assigning the x value to flashvars?
so.addVariable("cookie", x);
In which case , you should be able to retrieve it in Flash , by doing so in the Document Class:
var params:Object = this.loaderInfo.parameters;
var cookie:Object = params.cookie;
Do it with a flash cookie, but actually store the last time autoplayed, rather than a simple flag.