[SOLVED] How to construct video texture from pc.http.get request

pc.http.get(
        'https://www.youtube.com/shorts/fL4kLWjYYl4',
        {
            headers:
            {
                
            },
            async:true,
            cache:false,
            withCredentials:false,
            responseType: 'blob'
        },
        function (err, response) 
        {
            if(err)
            {
                console.log('came to error');
                console.log(err);
                return;
            }
        }
);

My question is how to create a video texture from the above code that is once my get request is successful I want to construct a videoasset and assign it to video.src = videoasset.getFileUrl(); is this possible in Playcanvas? The reason I want to do this way is because all our assets we require authentication so I pass authentication header along with get request.Please help

Hi need help on how to construct video asset from httprespose I already posted a question on this topic but here also I am asking below

pc.http.get(
https://www.youtube.com/shorts/fL4kLWjYYl4’,
{
headers:
{

        },
        async:true,
        cache:false,
        withCredentials:false,
        responseType: 'blob'
    },
    function (err, response) 
    {
        if(err)
        {
            console.log('came to error');
            console.log(err);
            return;
        }
    }

);

My question is how to create a video texture from the above code that is once my get request is successful I want to construct a videoasset and assign it to video.src = videoasset.getFileUrl(); is this possible in Playcanvas? The reason I want to do this way is because all our assets we require authentication so I pass authentication header along with get request.Please help

The YouTube link is a webpage, where you can watch the movie, add a comment, etc. It is not the video file source link. You are supposed to use Google API to request the source link. Refer to their docs:

yes u r right I gave that u tube url as dummy but in reality I have actual mp4 hosted on server and its https but its a private project. So my question is if I give valid url how to contruct video asset from response

Perhaps this way: PlayCanvas Examples

There are few playcanvas videoplayback projects / tutorials as well.

1 Like

I saw it it doesn’t server my purpose they give direct link but I want to do from http.get request. The reason is pretty simple because when we go from get request always we can pass headers. Please let me know if u find any source

Have you studied the response object? What errors do you have?

No I have not studied response object. Basically I try to download .mp4 file through get request and I get the response after the request I don’t know how to create a video asset from the response so that I can set video.src = vide asset.getFileUrl(). The error I get is operation can’t be completed for loading.

I would assume the response object should contain the needed info. You should refer to your server documentation on how to handle HTTP requests/responses and send data to browser client. This is outside of PlayCanvas scope. Once you get the URL, you can use the example given by @mvaligursky to create the video texture.

Guys I found solution on how to construct I think it will be helpful for someone out there

Load Image from get request

var LoadImageFromUrl = pc.createScript('loadImageFromUrl');
LoadImageFromUrl.attributes.add('url',{ type: 'string'});
// initialize code called once per entity
LoadImageFromUrl.prototype.initialize = function() {
var element = this.entity.findComponent("element");
    var self = this;
    pc.http.get(
        //sample link it won't work paste your actual link
        'https://app-sandbox/coverpage_icon.png',
        {
            headers:
            {
                "Client-ID": "Dummy"//If your get request uses authorisation header put here I used dummy
            },
             async:true,
             cache:false,
             withCredentials:false,
             responseType:pc.Http.ResponseType.BLOB
        },
        function (err, response) 
        {
            if(err)
            {
                console.log('came to error');
                console.log(err);
                return;
            }
            var imageURL = URL.createObjectURL(response);
            var filename = 'TestImage' + '.png';
            var file = {
            url: imageURL,
            filename: filename
            };
            var asset = new pc.Asset(filename, 'texture', file, null, null);
            asset.once('load', function (asset) {
                var element = self.entity.findComponent("element");
                if(element != null)
                    element.texture = asset.resource;
                URL.revokeObjectURL(imageURL);
            });
            self.app.assets.add(asset);
            self.app.assets.load(asset);
        }
    );
};

Load Json from get request

var LoadJsonFromUrl = pc.createScript('loadJsonFromUrl');

// initialize code called once per entity
LoadJsonFromUrl.prototype.initialize = function() {
    var self = this;
    pc.http.get(
        //sample link it won't work paste your actual link
        'https://app-sandbox/Json',
        {
            headers:
            {
             "Client-ID": "Dummy"//If your get request uses authorisation header put here I used dummy
            },
        },
        function (err, response) 
        {
            if(err)
            {
                console.log('came to error');
                console.log(err);
                return;
            }
            console.log(response);
        }
    );
};

**Load sound From get request**
var LoadSoundFromUrl = pc.createScript('loadSoundFromUrl');
// initialize code called once per entity
LoadSoundFromUrl.prototype.initialize = function() {
    var self = this;
    pc.http.get(
        //sample link it won't work paste your actual link
        'https://app-sandbox/background-music.mp3',
        {
            headers:
            {
                 "Client-ID": "Dummy"//If your get request uses authorisation header put here I used dummy
            },
            async:true,
            cache:false,
            withCredentials:false,
            responseType: pc.Http.ResponseType.BLOB
        },
        function (err, response) 
        {
            if(err)
            {
                console.log('came to error');
                console.log(err);
                return;
            }
            var soundUrl = URL.createObjectURL(response);
            var filename = 'TestMusic' + '.mp3';
            var file = {
            url: soundUrl,
            filename: filename
            };
            var asset = new pc.Asset(filename, 'audio', file, null, null);
            asset.once('load', function (asset) {
                var sound = self.entity.findComponent('sound');
                sound.addSlot('MySoundSlot', 
                {
                    loop: true,
                    asset: asset
                });
                sound.play('MySoundSlot');
                sound.positional = false;
                URL.revokeObjectURL(soundUrl);
            });
            self.app.assets.add(asset);
            self.app.assets.load(asset);
        }
    );
};

Load Video From get rquest

var LoadVideoFromUrl = pc.createScript('LoadVideoFromUrl');
LoadVideoFromUrl.attributes.add('screenMaterial', {
    title: 'Screen Material',
    description: 'The screen material of the TV that displays the video texture.',
    type: 'asset',
    assetType: 'material'
});
// initialize code called once per entity
LoadVideoFromUrl.prototype.initialize = function() {
    let self = this;
    this.loaded = false;
    pc.http.get(
        //sample link it won't work paste your actual link
        'https://app-sandbox/intro.mp4',
        {
            headers:
            {
               "Client-ID": "Dummy"//If your get request uses authorisation header put here I used dummy
            },
            async:true,
            cache:false,
            withCredentials:false,
            responseType: pc.Http.ResponseType.BLOB
        },
        function (err, response) 
        {
            if(err)
            {
                console.log('came to error');
                console.log(err);
                return;
            }
            self.videoUrl = URL.createObjectURL(response);
            console.log('Got video url');
            self.LoadAndSetUpVideo();
        }
  );
};

LoadVideoFromUrl.prototype.LoadAndSetUpVideo = function()
{
    // Create HTML Video Element to play the video
    let video = document.createElement('video');
    this.videoplayer = video;
    video.loop = true;

    // muted attribute is required for videos to autoplay
    video.muted = true;

    // critical for iOS or the video won't initially play, and will go fullscreen when playing
    video.playsInline = true;
    
    // autoplay the video
    video.autoplay = true;
    // iOS video texture playback requires that you add the video to the DOMParser
    // with at least 1x1 as the video's dimensions
    let style = video.style;
    style.width = '1px';
    style.height = '1px';
    style.position = 'absolute';
    style.opacity = '0';
    style.zIndex = '-1000';
    style.pointerEvents = 'none';

    document.body.appendChild(video);

    // Create a texture to hold the video frame data            
    this.videoTexture = new pc.Texture(this.app.graphicsDevice, {
         format: pc.PIXELFORMAT_RGB565,
        mipmaps: false,
        minFilter: pc.FILTER_LINEAR,
        magFilter: pc.FILTER_LINEAR,
        addressU: pc.ADDRESS_CLAMP_TO_EDGE,
        addressV: pc.ADDRESS_CLAMP_TO_EDGE
    });
    this.videoTexture.setSource(video);

    video.addEventListener('canplaythrough', function (e) {
        this.app.fire('PlayEvent', this.videoTexture);
    }.bind(this));
    this.app.on('PlayEvent', function (videoTexture) {
      this.loaded = true;   
      console.log('loaded');
    var material = this.screenMaterial.resource;
    material.emissiveMap = videoTexture;
    material.update();
}, this);
    // set video source
    video.src = this.videoUrl;    
    
    document.body.appendChild(video);
    video.load();

    this.on('destroy', function() {
        this.videoTexture.destroy();
        video.remove();
    }, this);
    this.app.mouse.on(pc.EVENT_MOUSEDOWN, this.onMouseDown, this);
}

LoadVideoFromUrl.prototype.onMouseDown = function()
{
    if (event.button === pc.MOUSEBUTTON_LEFT) {
        this.PlayPauseVideo();
    }
}

LoadVideoFromUrl.prototype.PlayPauseVideo = function()
{
    var videoElement = document.getElementsByTagName('video')[0];
    videoElement.muted = false;
    videoElement.volume = 1.0;
    videoElement.currentTime = 15;
    videoElement.play();
};

Load model from get request

var LoadModelUrl = pc.createScript('LoadModelFromUrl');
// initialize code called once per entity
LoadModelUrl.prototype.initialize = function() {
     this.LoadModel();
};
 
LoadModelUrl.prototype.LoadModel = function() {
     var self = this;
     pc.http.get(
         //sample link it won't work paste your actual link
        'https://sandboc/test.glb',
        {
            headers:
            {
                "Client-ID": "Dummy"//If your get request uses authorisation header put here I used dummy
   
            },
            async:true,
            cache:false,
            withCredentials:false,
            responseType: pc.Http.ResponseType.BLOB
        },
        function (err, response) 
        {
            if(err)
            {
                console.log('came to error');
                console.log(err);
                return;
            }
            var modelurl = URL.createObjectURL(response);

           var filename = 'TestModel' + '.glb';
        var file = {
            url: modelurl,
            filename: filename
        };
        var asset = new pc.Asset(filename, 'container', file, null, null);
        asset.once('load', function (containerAsset) {
           
                // As we play animations by name, if we have only one animation, keep it the same name as
                // the original container otherwise, postfix it with a number
                var animations = containerAsset.resource.animations;
                if (animations.length == 1) {
                    animations[0].name = assetName;
                } else if (animations.length > 1) {
                    for (var i = 0; i < animations.length; ++i) {
                        animations[i].name = assetName + ' ' + i.toString();
                    }
                }
        });

        self.app.assets.add(asset);
        self.app.assets.load(asset);
        self.InstantiateAsset(asset);
            URL.revokeObjectURL(modelurl);
     });
};

LoadModelUrl.prototype.InstantiateAsset = function(asset)
{
        var renderRootEntity = asset.resource.instantiateRenderEntity();
        this.entity.addChild(renderRootEntity);
        renderRootEntity.setLocalPosition(0, 0, 0);
}
1 Like