Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Ruby SDK for Shotstack, the cloud video editing API.

NotificationsYou must be signed in to change notification settings

shotstack/shotstack-sdk-ruby

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

49 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Ruby SDK for the ShotstackRuby video editor and cloud video editing API.

Shotstack is a cloud based video editing platform that enables the editing of videos using code.

The platform uses an API and a JSON format for specifying how videos should be edited and what asset and titles should be used.

A server based render farm takes care of rendering the videos allowing multiple videos to be created simultaneously.

For examples of how to use the SDK to create videos using code checkout the Ruby demo repo:https://github.com/shotstack/ruby-demos

Contents

Using the Ruby SDK

Installation

gem install shotstack

Video Editing

The Shotstack SDK enables programmatic video editing via the Edit APIrender endpoint. Prepare JSON edits using theprovided schema classes andPOST to the API for rendering.

Video Editing Example

The example below trims the start of a video clip and plays it for 8 seconds. The edit is prepared using the SDK modelsand then sent to the API for rendering.

require"shotstack"Shotstack.configuredo |config|config.api_key['x-api-key']="H7jKyj90kd09lbLOF7J900jNbSWS67X87xs9j0cD"config.host="api.shotstack.io"config.base_path="stage"endapi_client=Shotstack::EditApi.newvideo_asset=Shotstack::VideoAsset.new(src:"https://s3-ap-southeast-2.amazonaws.com/shotstack-assets/footage/skater.hd.mp4",trim:3)video_clip=Shotstack::Clip.new(asset:video_asset,start:0,length:8)track=Shotstack::Track.new(clips:[video_clip])timeline=Shotstack::Timeline.new(background:"#000000",tracks:[track])output=Shotstack::Output.new(format:"mp4",resolution:"sd")edit=Shotstack::Edit.new(timeline:timeline,output:output)response=api_client.post_render(edit).responseputsresponse.id

Status Check Example

The example request below can be called a few seconds after the render above is posted. It will return the status ofthe render, which can take several seconds to process.

require"shotstack"Shotstack.configuredo |config|config.api_key['x-api-key']="H7jKyj90kd09lbLOF7J900jNbSWS67X87xs9j0cD"config.host="api.shotstack.io"config.base_path="stage"endid="75143ec6-4b72-46f8-a67a-fd7284546935"# Use the render id from the previous exampleapi_client=Shotstack::EditApi.newresponse=api_client.get_render(id,{data:false,merged:true}).responseifresponse.status ==="done"putsresponse.url

Save a Template Example

The example below uses the Edit we create in theVideo Editing Example and saves it as atemplate. The template can be rendered at a later date and can include placeholders. Placeholders can be replacedwhen rendered usingmerge fields.

This example uses a placeholder for the video src (URL), trim (TRIM), and length (LENGTH) to allow you to trim any videousing a template.

require"shotstack"Shotstack.configuredo |config|config.api_key['x-api-key']="H7jKyj90kd09lbLOF7J900jNbSWS67X87xs9j0cD"config.host="api.shotstack.io"config.base_path="stage"endapi_client=Shotstack::EditApi.newvideo_asset=Shotstack::VideoAsset.new(src:"{{URL}}",trim:"{{TRIM}}")video_clip=Shotstack::Clip.new(asset:video_asset,start:0,length:"{{LENGTH}}")track=Shotstack::Track.new(clips:[video_clip])timeline=Shotstack::Timeline.new(background:"#000000",tracks:[track])output=Shotstack::Output.new(format:"mp4",resolution:"sd")edit=Shotstack::Edit.new(timeline:timeline,output:output)template=Shotstack::Template.new(name:"Trim Template",template:edit)response=api_client.post_template(template).responseputsresponse.id

Render a Template Example

The example below renders the template we created in the previous example and includes merge fields that will replacethe placeholders. Once submitted use the returned render ID and call theStatus Check Exampleto get the render progress.

require"shotstack"Shotstack.configuredo |config|config.api_key['x-api-key']="H7jKyj90kd09lbLOF7J900jNbSWS67X87xs9j0cD"config.host="api.shotstack.io"config.base_path="stage"endid="8aeabb0e-b5eb-8c5e-847d-82297dd4802a";# use the template id from previous exampleapi_client=Shotstack::EditApi.newmerge_field_url=Shotstack::MergeField.new(find:"URL",replace:"https://s3-ap-southeast-2.amazonaws.com/shotstack-assets/footage/skater.hd.mp4")merge_field_trim=Shotstack::MergeField.new(find:"TRIM",replace:3)merge_field_length=Shotstack::MergeField.new(find:"LENGTH",replace:6)template=Shotstack::TemplateRender.new(id:id,merge:[merge_field_url,merge_field_trim,merge_field_length])response=api_client.post_template_render(template).responseputsresponse.id

Video Editing Schemas

The following schemas are used to prepare a video edit.

Edit

AnEdit defines the arrangement of a video on a timeline, an audio edit or an image design and the output format.

Example:

require"shotstack"edit=Shotstack::Edit.new(timeline:timeline,output:output,merge:merge,callback:"https://my-server.com/callback.php",disk:"local")

Arguments:

ArgumentTypeDescriptionRequired
timelineShotstack::TimelineA timeline represents the contents of a video edit over time, an audio edit over time, in seconds, or an image layout. A timeline consists of layers called tracks. Tracks are composed of titles, images, audio, html or video segments referred to as clips which are placed along the track at specific starting point and lasting for a specific amount of time.-
outputShotstack::OutputThe output format, render range and type of media to generate.Y
mergeShotstack::MergeField[]An array of key/value pairs that provides an easy way to create templates with placeholders. The placeholders can be used to find and replace keys with values. For example you can search for the placeholder{{NAME}} and replace it with the valueJane.-
callbackstringAn optional webhook callback URL used to receive status notifications when a render completes or fails. Seewebhooks for more details.-
diskstring(Deprecated) The disk type to use for storing footage and asset for each render. Seedisk types for more details. [default tolocal]
  • local - optimized for high speed rendering with up to 512MB storage
  • mount - optimized for larger file sizes and longer videos with 5GB for source footage and 512MB for output render
-

Timeline

ATimeline represents the contents of a video edit over time, an audio edit over time, in seconds, or an image layout. A timeline consists of layers called tracks. Tracks are composed of titles, images, audio, html or video segments referred to as clips which are placed along the track at specific starting point and lasting for a specific amount of time.

Example:

require"shotstack"timeline=Shotstack::Timeline.new(soundtrack:soundtrack,background:'#000000',fonts:fonts,tracks:tracks,cache:true)

Arguments:

ArgumentTypeDescriptionRequired
soundtrackShotstack::SoundtrackA music or audio soundtrack file in mp3 format.-
backgroundstringA hexadecimal value for the timeline background colour. Defaults to#000000 (black).-
fontsShotstack::Font[]An array of custom fonts to be downloaded for use by the HTML assets.-
tracksShotstack::Track[]A timeline consists of an array of tracks, each track containing clips. Tracks are layered on top of each other in the same order they are added to the array with the top most track layered over the top of those below it. Ensure that a track containing titles is the top most track so that it is displayed above videos and images.Y
cacheboolDisable the caching of ingested source footage and assets. Seecaching for more details. [default totrue]-

Soundtrack

A music or audio file in mp3 format that plays for the duration of the rendered video or the length of the audio file, which ever is shortest.

Example:

require"shotstack"soundtrack=Shotstack::Soundtrack.new(src:'https://s3-ap-southeast-2.amazonaws.com/shotstack-assets/music/disco.mp3',effect:'fadeIn',volume:1)

Arguments:

ArgumentTypeDescriptionRequired
srcstringThe URL of the mp3 audio file. The URL must be publicly accessible or include credentials.Y
effectstringThe effect to apply to the audio file
  • fadeIn - fade volume in only
  • fadeOut - fade volume out only
  • fadeInFadeOut - fade volume in and out
-
volumefloatSet the volume for the soundtrack between 0 and 1 where 0 is muted and 1 is full volume (defaults to1).-

Font

Download a custom font to use with the HTML asset type, using the font name in the CSS or font tag. See ourcustom fonts getting started guide for more details.

Example:

require"shotstack"font=Shotstack::Font.new(src:'https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/fonts/OpenSans-Regular.ttf')

Arguments:

ArgumentTypeDescriptionRequired
srcstringThe URL of the font file. The URL must be publicly accessible or include credentials.Y

Track

A track contains an array of clips. Tracks are layered on top of each other in the order in the array. The top most track will render on top of those below it.

Example:

require"shotstack"track=Shotstack::Track(clips:clips)

Arguments:

ArgumentTypeDescriptionRequired
clipsShotstack::Clip[]An array of Clips comprising of TitleClip, ImageClip or VideoClip.Y

Clip

AClip is a container for a specific type of asset, i.e. a title, image, video, audio or html. You use a Clip to define when an asset will display on the timeline, how long it will play for and transitions, filters and effects to apply to it.

Example:

require"shotstack"clip=Shotstack::Clip.new(asset:asset,start:2,length:5,fit:'crop',scale:0,position:'center',offset:offset,transition:transition,effect:'zoomIn',filter:'greyscale',opacity:1,transform:transform)

Arguments:

ArgumentTypeDescriptionRequired
assetassetThe type of asset to display for the duration of this Clip. Value must be one of:Y
startfloatThe start position of the Clip on the timeline, in seconds.Y
lengthfloatThe length, in seconds, the Clip should play for.Y
fitstring fitSet how the asset should be scaled to fit the viewport using one of the following options [default tocrop]:
  • cover - stretch the asset to fill the viewport without maintaining the aspect ratio.
  • contain - fit the entire asset within the viewport while maintaining the original aspect ratio.
  • crop - scale the asset to fill the viewport while maintaining the aspect ratio. The asset will be cropped if it exceeds the bounds of the viewport.
  • none - preserves the original asset dimensions and does not apply any scaling.
-
scalefloatScale the asset to a fraction of the viewport size - i.e. ting the scale to 0.5 will scale asset to half the size of the viewport. This is useful for picture-in-picture video and scaling images such as logos and watermarks.-
positionstringPlace the asset in one of nine predefined positions of the viewport. This is most effective for when the asset is scaled and you want to position the element to a specific position [default tocenter].
  • top - top (center)
  • topRight - top right
  • right - right (center)
  • bottomRight - bottom right
  • bottom - bottom (center)
  • bottomLeft - bottom left
  • left - left (center)
  • topLeft - top left
  • center - center
-
offsetShotstack::OffsetOffset the location of the asset relative to its position on the viewport. The offset distance is relative to the width of the viewport - for example an x offset of 0.5 will move the asset half the viewport width to the right.-
transitionShotstack::TransitionIn and out transitions for a clip - i.e. fade in and fade out-
effectstringA motion effect to apply to the Clip.
  • zoomIn - slow zoom in
  • zoomOut - slow zoom out
  • slideLeft - slow slide (pan) left
  • slideRight - slow slide (pan) right
  • slideUp - slow slide (pan) up
  • slideDown - slow slide (pan) down
The motion effect speed can also be controlled by appendingFast orSlow to the effect, e.g.zoomInFast orslideRightSlow.
-
filterstringA filter effect to apply to the Clip.
  • boost - boost contrast and saturation
  • contrast - increase contrast
  • darken - darken the scene
  • greyscale - remove colour
  • lighten - lighten the scene
  • muted - reduce saturation and contrast
  • negative - invert colors
-
opacityfloats the opacity of the Clip where 1 is opaque and 0 is transparent. [default to1]-
transformShotstack::TransformationA transformation lets you modify the visual properties of a clip. Available transformations areShotstack::RotateTransformation,Shotstack::SkewTransformation andShotstack::FlipTransformation. Transformations can be combined to create interesting new shapes and effects.-

VideoAsset

TheVideoAsset is used to create video sequences from video files. The src must be a publicly accessible URL to a videoresource such as an mp4 file.

Example:

require"shotstack"video_asset=Shotstack::VideoAsset.new(src:'https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/footage/table-mountain.mp4',trim:5,volume:0.5,volume_effect:'fadeIn',crop:crop)

Arguments:

ArgumentTypeDescriptionRequired
srcstringThe video source URL. The URL must be publicly accessible or include credentials.Y
trimfloatThe start trim point of the video clip, in seconds (defaults to 0). Videos will start from the in trim point. The video will play until the file ends or the Clip length is reached.-
volumefloatSet the volume for the video clip between 0 and 1 where 0 is muted and 1 is full volume (defaults to 0).-
volume_effectstringThe volume effect to apply to the video asset.
  • fadeIn - fade volume in only
  • fadeOut - fade volume out only
  • fadeInFadeOut - fade volume in and out
-
cropShotstack::CropCrop the sides of an asset by a relative amount. The size of the crop is specified using a scale between 0 and 1, relative to the screen width - i.e. a left crop of 0.5 will crop half of the asset from the left, a top crop of 0.25 will crop the top by quarter of the asset.-

ImageAsset

TheImageAsset is used to create video from images to compose an image. The src must be a publicly accessible URL to an image resource such as a jpg or png file.

Example:

require"shotstack"image_asset=Shotstack::ImageAsset.new(src:'https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/images/earth.jpg',crop:crop)

Arguments:

ArgumentTypeDescriptionRequired
srcstringThe image source URL. The URL must be publicly accessible or include credentials.Y
cropShotstack::CropCrop the sides of an asset by a relative amount. The size of the crop is specified using a scale between 0 and 1, relative to the screen width - i.e. a left crop of 0.5 will crop half of the asset from the left, a top crop of 0.25 will crop the top by quarter of the asset.-

TitleAsset

TheTitleAsset clip type lets you create video titles from a text string and apply styling and positioning.

Example:

require"shotstack"title_asset=Shotstack::TitleAsset.new(text:'My Title',style:'minimal',color:'#ffffff',size:'medium',background:'#000000',position:'center',offset:offset)

Arguments:

ArgumentTypeDescriptionRequired
textstringThe title text string.Y
stylestringUses a preset to apply font properties and styling to the title.
  • minimal
  • blockbuster
  • vogue
  • sketchy
  • skinny
  • chunk
  • chunkLight
  • marker
  • future
  • subtitle
-
colorstringSet the text color using hexadecimal color notation. Transparency is supported by ting the first two characters of the hex string (opposite to HTML), i.e. #80ffffff will be white with 50% transparency [default to#ffffff].-
sizestringSet the relative size of the text using predefined sizes from xx-small to xx-large [default to 'medium'].
  • xx-small
  • x-small
  • small
  • medium
  • large
  • x-large
  • xx-large
-
backgroundstringApply a background color behind the text. Set the text color using hexadecimal color notation. Transparency is supported by ting the first two characters of the hex string (opposite to HTML), i.e. #80ffffff will be white with 50% transparency. Omit to use transparent background.-
positionstringPlace the title in one of nine predefined positions of the viewport [default tocenter.
  • top - top (center)
  • topRight - top right
  • right - right (center)
  • bottomRight - bottom right
  • bottom - bottom (center)
  • bottomLeft - bottom left
  • left - left (center)
  • topLeft - top left
  • center - center
-
offsetShotstack::OffsetOffset the location of the title relative to its position on the screen.-

HtmlAsset

TheHtmlAsset clip type lets you create text based layout and formatting using HTML and CSS. You can also set the height and width of a bounding box for the HTML content to sit within. Text and elements will wrap within the bounding box.

Example:

require"shotstack"html_asset=Shotstack::HtmlAsset.new(html:'<p>Hello <b>World</b></p>',css:'p { color: #ffffff; } b { color: #ffff00; }',width:400,height:200,background:'transparent',position:'center')

Arguments:

Argument | Type | Description | Required:--- | :--- | :---:html | string | The HTML text string. See list ofsupported HTML tags. | Ycss | string | The CSS text string to apply styling to the HTML. See list ofsupport CSS properties. | -width | int | Set the width of the HTML asset bounding box in pixels. Text will wrap to fill the bounding box. | -height | int | Set the height of the HTML asset bounding box in pixels. Text and elements will be masked if they exceed the height of the bounding box. | -background | string | Apply a background color behind the HTML bounding box using. Set the text color using hexadecimal color notation. Transparency is supported by ting the first two characters of the hex string (opposite to HTML), i.e. #80ffffff will be white with 80% transparency [default totransparent]. | -position | string | Place the HTML in one of nine predefined positions within the HTML area [default tocenter].

  • top - top (center)
  • topRight - top right
  • right - right (center)
  • bottomRight - bottom right
  • bottom - bottom (center)
  • bottomLeft - bottom left
  • left - left (center)
  • topLeft - top left
  • center - center
| -


AudioAsset

TheAudioAsset is used to add sound effects and audio at specific intervals on the timeline. The src must be apublicly accessible URL to an audio resource such as an mp3 file.

Example:

require"shotstack"audio_asset=Shotstack::AudioAsset.new(src:'https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/music/unminus/lit.mp3',trim:2,volume:0.5,effect:'fadeInFadeOut')

Arguments:

ArgumentTypeDescriptionRequired
srcstringThe audio source URL. The URL must be publicly accessible or include credentials.Y
trimfloatThe start trim point of the audio clip, in seconds (defaults to 0). Audio will start from the trim point. The audio will play until the file ends or the Clip length is reached.-
volumefloatSet the volume for the audio clip between 0 and 1 where 0 is muted and 1 is full volume (defaults to 1).-
effectstringThe effect to apply to the audio asset:
  • fadeIn - fade volume in only
  • fadeOut - fade volume out only
  • fadeInFadeOut - fade volume in and out
-

LumaAsset

TheLumaAsset is used to create luma matte masks, transitions and effects between other assets. A luma matte is a grey scale image or animated video where the black areas are transparent and the white areas solid. The luma matte animation should be provided as an mp4 video file. The src must be a publicly accessible URL to the file.

Example:

require"shotstack"luma_asset=Shotstack::LumaAsset.new(src:'https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/examples/luma-mattes/paint-left.mp4',trim:5)

Arguments:

ArgumentTypeDescriptionRequired
srcstringThe luma matte source URL. The URL must be publicly accessible or include credentials.Y
trimfloatThe start trim point of the luma matte clip, in seconds (defaults to 0). Videos will start from the in trim point. A luma matte video will play until the file ends or the Clip length is reached.-

Transition

TheTransition clip type lets you define in and out transitions for a clip - i.e. fade in and fade out

Example:

require"shotstack"transition=Shotstack::Transition.new(in:'fade',out:'fade')

Arguments:

ArgumentTypeDescriptionRequired
instringThe transition in. Available transitions are:
  • fade - fade in
  • reveal - reveal from left to right
  • wipeLeft - fade across screen to the left
  • wipeRight - fade across screen to the right
  • slideLeft - move slightly left and fade in
  • slideRight - move slightly right and fade in
  • slideUp - move slightly up and fade in
  • slideDown - move slightly down and fade in
  • carouselLeft - slide in from right to left
  • carouselRight - slide in from left to right
  • carouselUp - slide in from bottom to top
  • carouselDown - slide in from top to bottom
  • shuffleTopRight - rotate in from top right
  • shuffleRightTop - rotate in from right top
  • shuffleRightBottom - rotate in from right bottom
  • shuffleBottomRight - rotate in from bottom right
  • shuffleBottomLeft - rotate in from bottom left
  • shuffleLeftBottom - rotate in from left bottom
  • shuffleLeftTop - rotate in from left top
  • shuffleTopLeft - rotate in from top left
  • zoom - fast zoom in
The transition speed can also be controlled by appendingFast orSlow to the transition, e.g.fadeFast orCarouselLeftSlow.
-
outstringThe transition out. Available transitions are:
  • fade - fade out
  • reveal - reveal from right to left
  • wipeLeft - fade across screen to the left
  • wipeRight - fade across screen to the right
  • slideLeft - move slightly left and fade out
  • slideRight - move slightly right and fade out
  • slideUp - move slightly up and fade out
  • slideDown - move slightly down and fade out
  • carouselLeft - slide out from right to left
  • carouselRight - slide out from left to right
  • carouselUp - slide out from bottom to top
  • carouselDown - slide out from top to bottom
  • shuffleTopRight - rotate out from top right
  • shuffleRightTop - rotate out from right top
  • shuffleRightBottom - rotate out from right bottom
  • shuffleBottomRight - rotate out from bottom right
  • shuffleBottomLeft - rotate out from bottom left
  • shuffleLeftBottom - rotate out from left bottom
  • shuffleLeftTop - rotate out from left top
  • shuffleTopLeft - rotate out from top left
  • zoom - fast zoom out
The transition speed can also be controlled by appendingFast orSlow to the transition, e.g.fadeFast orCarouselLeftSlow.
-

Offset

Offs the position of an asset horizontally or vertically by a relative distance.

Example:

require"shotstack"offset=Shotstack::Offset.new(x:0.1,y: -0.2)

Arguments:

ArgumentTypeDescriptionRequired
xfloatOffset an asset on the horizontal axis (left or right), range varies from -10 to 10. Positive numbers move the asset right, negative left. For all asset except titles the distance moved is relative to the width of the viewport - i.e. an X offset of 0.5 will move the asset half the screen width to the right. [default to0]-
yfloatOffset an asset on the vertical axis (up or down), range varies from -10 to 10. Positive numbers move the asset up, negative down. For all asset except titles the distance moved is relative to the height of the viewport - i.e. an Y offset of 0.5 will move the asset up half the screen height. [default to0]-

Crop

Crop the sides of an asset by a relative amount. The size of the crop is specified using a scale between 0 and 1, relative to the screen width - i.e a left crop of 0.5 will crop half of the asset from the left, a top crop of 0.25 will crop the top by quarter of the asset.

Example:

require"shotstack"crop=Shotstack::Crop.new(top:0.15,bottom:0.15,left:0,right:0)

Arguments:

ArgumentTypeDescriptionRequired
topfloatCrop from the top of the asset-
bottomfloatCrop from the bottom of the asset-
leftfloatCrop from the left of the asset-
rightfloatCrop from the right of the asset-

Transformation

Apply one or more transformations to a clip.Transformations alter the visual properties of a clip and can be combined to create new shapes and effects.

Example:

require"shotstack"transformation=Shotstack::Transformation.new(rotate:rotate,skew:skew,flip:flip)

Arguments:

ArgumentTypeDescriptionRequired
rotateShotstack::RotateTransformationRotate a clip by the specified angle in degrees. Rotation origin is set based on the clipsposition.-
skewShotstack::SkewTransformationSkew a clip so its edges are sheared at an angle. Use values between 0 and 3. Over 3 the clip will be skewed almost flat.-
flipShotstack::FlipTransformationFlip a clip vertically or horizontally. Acts as a mirror effect of the clip along the selected plane.-

RotateTransformation

Rotate a clip by the specified angle in degrees. Rotation origin is set based on the clipsposition.

Example:

require"shotstack"rotate_transformation=Shotstack::RotateTransformation.new(angle:45)

Arguments:

ArgumentTypeDescriptionRequired
angleintThe angle to rotate the clip. Can be 0 to 360, or 0 to -360. Using a positive number rotates the clip clockwise, negative numbers counter-clockwise.-

SkewTransformation

Skew a clip so its edges are sheared at an angle. Use values between 0 and 3. Over 3 the clip will be skewed almost flat.

Example:

require"shotstack"skew_transformation=Shotstack::SkewTransformation.new(x:0.5,y:0.5)

Arguments:

ArgumentTypeDescriptionRequired
xfloatSkew the clip along it's x axis. [default to0]-
yfloatSkew the clip along it's y axis. [default to0]-

FlipTransformation

Flip a clip vertically or horizontally. Acts as a mirror effect of the clip along the selected plane.

Example:

require"shotstack"flip_transformation=Shotstack::FlipTransformation.new(horizontal:true,vertical:true)

Arguments:

ArgumentTypeDescriptionRequired
horizontalboolFlip a clip horizontally. [default tofalse]-
verticalboolFlip a clip vertically. [default tofalse]-

MergeField

A merge field consists of a key;find, and avalue; replace. Merge fields can be used to replace placeholders within the JSON edit to create re-usable templates. Placeholders should be a string with double brace delimiters, i.e."{{NAME}}". A placeholder can be used for any value within the JSON edit.

Example:

require"shotstack"merge_field=Shotstack::MergeField.new(find:'NAME',replace:'Jane')

Arguments:

ArgumentTypeDescriptionRequired
findstringThe string to find without delimiters.Y
replacereplaceThe replacement value. The replacement can be any valid JSON type - string, boolean, number, etc...Y

Template Schemas

The following schemas specify how to use templates to store and render templates. A template lets you save anEdit that can be rendered by its template ID and optionally include merge fields that are merged with thetemplate when rendered.

Template

A template is a savedEdit than can be loaded and re-used.

Example:

require"shotstack"template=Shotstack::Template.new(name:'My Template',template:edit)

Arguments:

ArgumentTypeDescriptionRequired
namestringThe template name.Y
templateShotstack::EditAn edit defines the arrangement of a video on a timeline, an audio edit or an image design and the output format.Y

TemplateRender

Configure the id and optional merge fields to render a template by id.

Example:

require"shotstack"template=Shotstack::TemplateRender.new(id:'21e781c0-8232-4418-fec1-cc99f0280c21',merge:merge)

Arguments:

ArgumentTypeDescriptionRequired
idstringThe id of the template to render in UUID format.Y
mergeShotstack::MergeField[]An array of key/value pairs that provides an easy way to create templates with placeholders. The placeholders can be used to find and replace keys with values. For example you can search for the placeholder{{NAME}} and replace it with the valueJane.-

Output Schemas

The following schemas specify the output format and tings.

Output

The output format, render range and type of media to generate.

Example:

require"shotstack"output=Shotstack::Output.new(format:'mp4',resolution:'sd',aspectRatio:'16:9',size:size,fps:25,scale_to:'preview',quality:'medium',repeat:true,mute:false,range:range,poster:poster,thumbnail:thumbnail,destinations:destinations)

Arguments:

ArgumentTypeDescriptionRequired
formatstringThe output format and type of media file to generate.
  • mp4 - mp4 video file
  • gif - animated gif
  • jpg - jpg image file
  • png - png image file
  • bmp - bmp image file
  • mp3 - mp3 audio file (audio only)
Y
resolutionstringThe output resolution of the video or image.
  • preview - 512px x 288px @ 15fps
  • mobile - 640px x 360px @ 25fps
  • sd - 1024px x 576px @ 25fps
  • hd - 1280px x 720px @ 25fps
  • 1080 - 1920px x 1080px @ 25fps
-
aspectRatiostringThe aspect ratio (shape) of the video or image. Useful for social media output formats. Options are:
  • 16:9 - regular landscape/horizontal aspect ratio (default)
  • 9:16 - vertical/portrait aspect ratio
  • 1:1 - square aspect ratio
  • 4:5 - short vertical/portrait aspect ratio
  • 4:3 - legacy TV aspect ratio
-
sizeShotstack::SizeSet a custom size for a video or image. When using a custom size omit theresolution andaspectRatio. Custom sizes must be divisible by 2 based on the encoder specifications.-
fpsfloatOverride the default frames per second. Useful for when the source footage is recorded at 30fps, i.e. on mobile devices. Lower frame rates can be used to add cinematic quality (24fps) or to create smaller file size/faster render times or animated gifs (12 or 15fps). Default is 25fps.
  • 12 - 12fps
  • 15 - 15fps
  • 23.976 - 23.976fps
  • 24 - 24fps
  • 29.97 - 29.97fps
  • 25 - 25fps
  • 30 - 30fps
-
scaleTostringOverride the resolution and scale the video or image to render at a different size. When using scaleTo the asset should be edited at the resolution dimensions, i.e. use font sizes that look best at HD, then use scaleTo to output the file at SD and the text will be scaled to the correct size. This is useful if you want to create multiple asset sizes.
  • preview - 512px x 288px @ 15fps
  • mobile - 640px x 360px @ 25fps
  • sd - 1024px x 576px @25fps
  • hd - 1280px x 720px @25fps
  • 1080 - 1920px x 1080px @25fps
-
qualitystringAdjust the output quality of the video, image or audio. Adjusting quality affects render speed, download speeds and storage requirements due to file size. The defaultmedium provides the most optimized choice for all three factors.
  • low - slightly reduced quality, smaller file size
  • medium - optimized quality, render speeds and file size
  • high - slightly increased quality, larger file size
-
repeatboolLoop tings for gif files. Set totrue to loop,false to play only once. [default totrue]-
muteboolMute the audio track of the output video. Set totrue to mute,false to un-mute.-
rangeShotstack::RangeSpecify a time range to render, i.e. to render only a portion of a video or audio file. Omit this ting to export the entire video. Range can also be used to render a frame at a specific time point - ting a range and output format asjpg will output a single frame image at the rangestart point.-
posterShotstack::PosterGenerate a poster image from a specific point on the timeline.-
thumbnailShotstack::ThumbnailGenerate a thumbnail image from a specific point on the timeline.-
destinationsShotstack::Destinations[]A destination is a location where output files can be sent to for serving or hosting. By default all rendered assets are automatically sent to the Shotstack hosting destination.-

Size

Set a custom size for a video or image. When using a custom size omit theresolution andaspectRatio. Custom sizes must be divisible by 2 based on the encoder specifications.

Example:

require"shotstack"size=Shotstack::Size.new(width:1200,height:800)

Arguments:

ArgumentTypeDescriptionRequired
widthintSet a custom width for the video or image file. Value must be divisible by 2. Maximum video width is 1920px, maximum image width is 4096px.-
heightintSet a custom height for the video or image file. Value must be divisible by 2. Maximum video height is 1920px, maximum image height is 4096px.-

Range

Specify a time range to render, i.e. to render only a portion of a video or audio file. Omit this ting to export the entire video. Range can also be used to render a frame at a specific time point - ting a range and output format asjpg will output a single frame image at the rangestart point.

Example:

require"shotstack"range=Shotstack::Range.new(start:3,length:6)

Arguments:

ArgumentTypeDescriptionRequired
startfloatThe point on the timeline, in seconds, to start the render from - i.e. start at second 3.-
lengthfloatThe length of the portion of the video or audio to render - i.e. render 6 seconds of the video.-

Poster

Generate aPoster image for the video at a specific point from the timeline. The poster image size will match the size of the output video.

Example:

require"shotstack"poster=Shotstack::Poster.new(capture:1)

Arguments:

ArgumentTypeDescriptionRequired
capturefloatThe point on the timeline in seconds to capture a single frame to use as the poster image.Y

Thumbnail

Generate a thumbnail image for the video or image at a specific point from the timeline.

Example:

require"shotstack"thumbnail=Shotstack::Thumbnail.new(capture:1,scale:0.3)

Arguments:

ArgumentTypeDescriptionRequired
capturefloatThe point on the timeline in seconds to capture a single frame to use as the thumbnail image.Y
scalefloatScale the thumbnail size to a fraction of the viewport size - i.e. ting the scale to 0.5 will scale the thumbnail to half the size of the viewport.Y

Destinations

ShotstackDestination

Send rendered asset to the Shotstack hosting and CDN service. This destination is enabled by default.

Example:

require"shotstack"shotstack_destination=Shotstack::ShotstackDestination.new(provider:'shotstack',exclude:false)

Arguments:

ArgumentTypeDescriptionRequired
providerstringThe destination to send rendered assets to - set toshotstack for Shotstack.Y
excludeboolSet totrue to opt-out from the Shotstack hosting and CDN service. All files must be downloaded within 24 hours of rendering. [default tofalse]-

MuxDestination

Send rendered videos to theMux video hosting andstreaming service. Mux credentials are required and added via thedashboard, not in the request.

Example:

require"shotstack"mux_destination=Shotstack::MuxDestination.new(provider:'mux',options:mux_destination_options)

Arguments:

ArgumentTypeDescriptionRequired
providerstringThe destination to send rendered assets to - set tomux for Mux.Y
optionsShotstack::MuxDestinationOptionsAdditional Mux configuration and features.-

MuxDestinationOptions

Pass additional options to control how Mux processes video. Currently supports playback policy option.

Example:

mux_destination_options = Shotstack::MuxDestinationOptions.new(playback_policy: ['public'])

#### Arguments:Argument | Type | Description | Required:--- | :--- | :--- | :---: playback_policy | [string] | Sets the Mux `playback_policy` option. Value is an array of strings - use **public**, **signed**, or both. | -  ### S3DestinationSend rendered videos to an [Amazon S3](https://shotstack.io/docs/guide/serving-assets/destinations/s3) bucket. Send files to any region with your own prefix and filename. AWS credentials are required and added via the [dashboard](https://dashboard.shotstack.io/integrations/s3), not in the request.#### Example:```pythonrequire "shotstack"const s3_destination = new Shotstack::S3Destination.new(  provider: 's3',  options: S3_destination_options)

Arguments:

ArgumentTypeDescriptionRequired
providerstringThe destination to send rendered assets to - set tos3 for S3.Y
optionsS3DestinationOptionsAdditional S3 configuration options.-

S3DestinationOptions

Pass additional options to control how files are stored in S3.

Example:

require"shotstack"consts3_destination_options=newShotstack::S3DestinationOptions.new(region:'us-east-1',bucket:'my-bucket',prefix:'my-renders',filename:'my-file',acl:'public-read',)

Arguments:

ArgumentTypeDescriptionRequired
regionstringChoose the region to send the file to. Must be a validAWS region string likeus-east-1 orap-southeast-2Y
bucketstringThe bucket name to send files to. The bucket must exist in the AWS account before files can be sent.Y
prefixstringA prefix for the file being sent. This is typically a folder name, i.e.videos orcustomerId/videos.-
filenamestringUse your own filename instead of the default render ID filename. Note: omit the file extension as this will be appended depending on the output format. Also-poster.jpg and-thumb.jpg will be appended for poster and thumbnail images.-
aclstringSets the S3 Access Control List (acl) permissions. Default isprivate. Must use a valid S3Canned ACL.-

Render Response Schemas

The following schemas are returned by the render request and status request.

QueuedResponse

The response received after arender request is submitted. The render task is queued for rendering and a unique render id is returned.

Attributes:

AttributeTypeDescriptionRequired
successbooltrue if successfully queued, elsefalse.Y
messagestringCreated,Bad Request or an error message.Y
responseShotstack::QueuedResponseDataQueuedResponseData or an error message.Y

QueuedResponseData

TheQueuedResponseData is the response data returned with theQueuedResponse.

Attributes:

AttributeTypeDescriptionRequired
messagestringSuccess response message or error details.Y
idstringThe id of the render task in UUID format.Y

RenderResponse

TheRenderResponse is the response received after arender status request is submitted. The response includes details about status of a render and the output URL.

Attributes:

AttributeTypeDescriptionRequired
successbooltrue if status available, elsefalse.Y
messagestringOK or an error message.Y
responseShotstack::RenderResponseDataRenderResponse or an error message.Y

RenderResponseData

TheRenderResponseData is the response data returned with theRenderResponse request including status and URL.

Arguments:

ArgumentTypeDescriptionRequired
idstringThe id of the render task in UUID format.Y
ownerstringThe owner id of the render task.Y
planstringThe customer subscription plan.-
statusstringThe status of the render task.
  • queued - render is queued waiting to be rendered
  • fetching - asset are being fetched
  • rendering - the asset is being rendered
  • saving - the final asset is being saved to storage
  • done - the asset is ready to be downloaded
  • failed - there was an error rendering the asset
Y
errorstringAn error message, only displayed if an error occurred.-
durationfloatThe output video or audio length in seconds.-
render_timefloatThe time taken to render the asset in milliseconds.-
urlstringThe URL of the final asset. This will only be available if status is done. This is a temporary URL and will be deleted after 24 hours. By default all asset are copied to the Shotstack hosting and CDN destination.-
posterstringThe URL of the poster image if requested. This will only be available if status is done.-
thumbnailstringThe URL of the thumbnail image if requested. This will only be available if status is done.-
dataShotstack::EditThe timeline and output data to be rendered.Y
createdstringThe time the render task was initially queued.Y
updatedstringThe time the render status was last updated.Y

Template Response Schemas

The following schemas are returned by the templates endpoint, including create, update and rendering a template.

TemplateResponse

The response received after atemplate is submitted. The template is saved and a uniquetemplate id is returned.

Arguments:

ArgumentTypeDescriptionRequired
successbooltrue if successfully created, elsefalse.Y
messagestringCreated,Bad Request or an error message.Y
responseShotstack::TemplateResponseDataTemplateResponseData or an error message.Y

TemplateResponseData

The response data returned with theShotstack.TemplateResponse.

Arguments:

ArgumentTypeDescriptionRequired
messagestringSuccess response message or error details.Y
idstringThe unique id of the template in UUID format.Y

TemplateDataResponse

The template data including the template name andEdit.

Arguments:

ArgumentTypeDescriptionRequired
successbooltrue if successfully returned, elsefalse.Y
messagestringOK,Bad Request or an error message.Y
responseShotstack::TemplateDataResponseDataTemplateDataResponseData or an error message.Y

TemplateDataResponseData

The response data returned with theTemplateDataResponse.

Arguments:

ArgumentTypeDescriptionRequired
idstringThe unique id of the template in UUID format.Y
namestringThe template name.Y
ownerstringThe owner id of the templates.Y
templateShotstack::EditEdit or an error message.Y

TemplateListResponse

A list of previously saved templates.

Arguments:

ArgumentTypeDescriptionRequired
successbooltrue if successfully returned, elsefalse.Y
messagestringOK,Bad Request or an error message.Y
responseShotstack::TemplateListResponseDataTemplateListResponseData or an error message.Y

TemplateListResponseData

The response data returned with theTemplateListResponse.

Arguments:

ArgumentTypeDescriptionRequired
ownerboolThe owner id of the templates.Y
templatesShotstack::TemplateListResponseItem[]The list of templates.Y

TemplateListResponseItem

The individual template item returned with theTemplateListResponseData templateslist.

Arguments:

ArgumentTypeDescriptionRequired
idstringThe unique id of the template in UUID format.Y
namestringThe template nameY
createdstringThe time the template was created.-
updatedstringThe time the template was last updated.-

Inspecting Media

The SDKprobe endpoint can be used to inspect media hosted online. Simply pass the URL of an asset to inspect.

Probe Example

The example below inspects (probes) a video hosted on GitHub and returns metadata about the file.

require"shotstack"Shotstack.configuredo |config|config.api_key['x-api-key']="H7jKyj90kd09lbLOF7J900jNbSWS67X87xs9j0cD"config.host="api.shotstack.io"config.base_path="stage"endurl="https://github.com/shotstack/test-media/raw/main/captioning/scott-ko.mp4"api_client=Shotstack::EditApi.newbeginresponse=api_client.probe(url).responserescue=>errorabort("Request failed:#{error.message}")endresponse[:metadata][:streams].each_with_indexdo |stream,index|ifstream[:codec_type] ==='video'puts"Example settings for:#{response[:metadata][:format][:filename]}"puts"Width:#{stream[:width]}px"puts"Height:#{stream[:height]}px"puts"Framerate:#{stream[:r_frame_rate]} fps"puts"Duration:#{stream[:duration]} secs"endend

Probe Schemas

The following schemas are returned by the probe request.

ProbeResponse

TheProbeResponse is the response returned after aprobe request is submitted. The probe requests returns data from FFprobe formatted as JSON.

Arguments:

ArgumentTypeDescriptionRequired
successbooltrue if media successfully read, elsefalse.Y
messagestringCreated,Bad Request or an error message.Y
responseobjectThe response from FFprobe in JSON formatY

Managing Assets

By default, all assets generated by the editing API are hosted by Shotstack and served via our CDN. The SDK providesaccess to the Serve API to retrieve information about hosted files. Files can also be deleted.

Assets by Render ID Example

The example below uses a render ID to look up hosted assets associated with the render. Note that multiple assets can becreated for a render, i.e. video, thumb and poster. Each asset has a unique asset ID different to the render ID.

require"shotstack"Shotstack.configuredo |config|config.api_key['x-api-key']="H7jKyj90kd09lbLOF7J900jNbSWS67X87xs9j0cD"config.host="api.shotstack.io"config.base_path="serve/stage"endid="140924c6-077d-4334-a89f-94befcfc0155"api_client=Shotstack::ServeApi.newbegindata=api_client.get_asset_by_render_id(id).datarescue=>errorabort("Request failed:#{error.message}")enddata.eachdo |asset|caseasset.attributes.statuswhen"failed"puts">> Something went wrong, asset could not be copied."elseputs"Status:#{asset.attributes.status}"puts">> Asset CDN URL:#{asset.attributes.url}"puts">> Asset ID:#{asset.attributes.id}"puts">> Render ID:#{asset.attributes.render_id}"endend

Assets by Asset ID Example

Every asset has a unique asset ID, the example below looks up an asset by its asset ID.

require"shotstack"Shotstack.configuredo |config|config.api_key['x-api-key']="H7jKyj90kd09lbLOF7J900jNbSWS67X87xs9j0cD"config.host="api.shotstack.io"config.base_path="serve/stage"endid="ed43eae3-4825-4c03-979d-f7dc47b9997c"api_client=Shotstack::ServeApi.newbeginasset=api_client.get_asset(id).datarescue=>errorabort("Request failed:#{error.message}")endcaseasset.attributes.statuswhen"failed"puts">> Something went wrong, asset could not be copied."elseputs"Status:#{asset.attributes.status}"puts">> Asset CDN URL:#{asset.attributes.url}"puts">> Asset ID:#{asset.attributes.id}"puts">> Render ID:#{asset.attributes.render_id}"end

Asset Schemas

The following schemas are returned by requests to the Serve API.

AssetResponse

TheAssetResponse is the response returned by the Serve APIget asset request. Includes details of a hosted video, image, audio file, thumbnail or poster image. The response follows thejson:api specification.

Arguments:

ArgumentTypeDescriptionRequired
dataShotstack::AssetResponseDataReturns an asset resource.-

AssetRenderResponse

TheAssetRenderResponse is the response returned by the Serve APIget asset by render id request. The response is an array of asset resources, including video, image, audio, thumbnail and poster image. The response follows thejson:api specification.

Arguments:

ArgumentTypeDescriptionRequired
dataShotstack::AssetResponseData[]Returns an array of asset resources grouped by render id.-

AssetResponseData

TheAssetResponseData contains the type of resource (an asset) and attributes of the asset.

Arguments:

ArgumentTypeDescriptionRequired
typestringThe type of resource, in this case it is anasset.-
attributesShotstack::AssetResponseAttributesThe asset attributes including render id, url, filename, file size, etc...-

AssetResponseAttributes

TheAssetResponseAttributes contains the list of asset attributes and their values.

Arguments:

ArgumentTypeDescriptionRequired
idstringThe unique id of the hosted asset in UUID format.-
ownerstringThe owner id of the render task.-
regionstringThe region the asset is hosted, currently onlyau (Australia).-
render_idstringThe original render id that created the asset in UUID format. Multiple asset can share the same render id.-
filenamestringThe asset file name.-
urlstringThe asset file name.-
statusstringThe status of the asset.
  • importing - the asset is being copied to the hosting service
  • ready - the asset is ready to be served to users
  • failed - the asset failed to copy or delete
  • deleted - the asset has been deleted
-
createdstringThe time the asset was created.-
updatedstringThe time the asset status was last updated.-

API Documentation and Guides


[8]ページ先頭

©2009-2025 Movatter.jp