Lire des vidéos

Godot supporte la lecture de vidéos avec le nœud VideoStreamPlayer.

Formats de lecture pris en charge

The only supported format in core is Ogg Theora (not to be confused with Ogg Vorbis audio) with optional Ogg Vorbis audio tracks. It's possible for extensions to bring support for additional formats.

Les normes H.264 et H.265 ne peuvent pas être supportées par le noyau Godot, ceux-ci étant des technologies brevetées. AV1 est libre de droit, mais reste lent à décoder sur le CPU et le support du décodage matériel n'est pas encore disponible sur tous les GPUs utilisés aujourd'hui.

WebM was supported in core in Godot 3.x, but support for it was removed in 4.0 as it was too buggy and difficult to maintain.

Note

Vous pouvez trouver des vidéos avec une extension .ogg ou .ogx, qui sont des extensions génériques pour les données d'un conteneur Ogg.

Renommer ces extensions de fichiers en .ogv peut permettre à ces vidéos d'être importées dans Godot. Cependant, tous les fichiers avec des extensions .ogg ou .ogx ne sont pas forcément des vidéos - certaines d'entre elles peuvent ne contenir que de l'audio.

Setting up VideoStreamPlayer

  1. Create a VideoStreamPlayer node using the Create New Node dialog.

  2. Select the VideoStreamPlayer node in the scene tree dock, go to the inspector and load an .ogv file in the Stream property.

  3. If you want the video to play as soon as the scene is loaded, check Autoplay in the inspector. If not, leave Autoplay disabled and call play() on the VideoStreamPlayer node in a script to start playback when desired.

Gérer le redimensionnement et différents rapports d'aspect

By default in Godot 4.0, the VideoStreamPlayer will automatically be resized to match the video's resolution. You can make it follow usual Control sizing by enabling Expand on the VideoStreamPlayer node.

To adjust how the VideoStreamPlayer node resizes depending on window size, adjust the anchors using the Layout menu at the top of the 2D editor viewport. However, this setup may not be powerful enough to handle all use cases, such as playing fullscreen videos without distorting the video (but with empty space on the edges instead). For more control, you can use an AspectRatioContainer node, which is designed to handle this kind of use case:

Ajoutez un nœud AspectRatioContainer. Vérifiez que ce ne soit pas l'enfant d'un autre nœud conteneur. Sélectionnez le nœud AspectRatioContainer, puis réglez sa Disposition en haut de l'éditeur 2D à Rectangle complet. Réglez le Ratio dans le nœud AspectRatioContainer afin qu'il corresponde aux proportions de la vidéo. Vous pouvez utiliser des formules mathématiques dans l'inspecteur pour vous aider. Souvenez-vous de faire en sorte qu'une des opérandes soit un flottant. Sinon, le résultat de la division sera toujours un entier.

La propriété Ratio de l'AspectRatioContainer est en cours de modification dans l'inspecteur de l'éditeur

Ce sera évalué à (approximativement) 1.777778

Once you've configured the AspectRatioContainer, reparent your VideoStreamPlayer node to be a child of the AspectRatioContainer node. Make sure Expand is enabled on the VideoStreamPlayer. Your video should now scale automatically to fit the whole screen while avoiding distortion.

Voir aussi

Voir Résolutions multiples pour plus d'informations sur le support de plusieurs rapports d'aspect dans votre projet.

Afficher une vidéo sur une surface 3D

En utilisant un nœud VideoStreamPlayer comme enfant d'un nœud SubViewport, il est possible d'afficher n'importe quel nœud 2D sur une surface 3D. Par exemple, cela peut être utilisé pour afficher des billboards animés quand l'animation trame par trame nécessiterait trop de mémoire.

Ceci peut être fait avec les étapes suivantes :

  1. Créez un nœud SubViewport. Réglez sa taille pour qu'il corresponde à la taille de votre vidéo en pixels.

  2. Create a VideoStreamPlayer node as a child of the SubViewport node and specify a video path in it. Make sure Expand is disabled, and enable Autoplay if needed.

  3. Créez un nœud MeshInstance3D avec une ressource PlaneMesh ou QuadMesh dans la propriété Mesh. Redimensionnez le maillage pour qu'il corresponde au format de la vidéo (sinon, celle-ci apparaîtra déformée).

  4. Create a new StandardMaterial3D resource in the Material Override property in the GeometryInstance3D section.

  5. Activez Local à la scène dans la section Ressource du StandardMaterial3D (en bas). Cela est requis avant que vous puissiez utiliser une ViewportTexture dans sa propriété Texture Albedo.

  6. In the StandardMaterial3D, set the Albedo > Texture property to New ViewportTexture. Edit the new resource by clicking it, then specify the path to the SubViewport node in the Viewport Path property.

  7. Enable Albedo Texture Force sRGB in the StandardMaterial3D to prevent colors from being washed out.

  8. If the billboard is supposed to emit its own light, set Shading Mode to Unshaded to improve rendering performance.

Voir Utilisation de Viewports et la démo de GUI en 3D pour plus d'informations sur la mise en place.

Looping a video

For looping a video, the Loop property can be enabled. This will seamlessly restart the video when it reaches its end.

Note that setting the project setting Video Delay Compensation to a non-zero value might cause your loop to not be seamless, because the synchronization of audio and video takes place at the start of each loop causing occasional missed frames. Set Video Delay Compensation in your project settings to 0 to avoid frame drop issues.

Limites de la lecture

L'implémentation actuelle de la lecture vidéo dans Godot présente plusieurs limitations :

  • Lancer la vidéo à un moment précis n'est pas pris en charge.

  • Changing playback speed is not supported. VideoStreamPlayer also won't follow Engine.time_scale.

  • Le streaming d'une vidéo à partir d'une URL n'est pas prise en charge.

  • Only mono and stereo audio output is supported.

Clé Chroma de vidéos

Chroma key, commonly known as the "green screen" or "blue screen" effect, allows you to remove a specific color from an image or video and replace it with another background. This effect is widely used in video production to composite different elements together seamlessly.

../../_images/chroma_key_video.webp

We will achieve the chroma key effect by writing a custom shader in GDScript and using a VideoStreamPlayer node to display the video content.

Scene Setup

Ensure that the scene contains a VideoStreamPlayer node to play the video and a Control node to hold the UI elements for controlling the chroma key effect.

../../_images/chroma_key_scene.webp

Writing the Custom Shader

To implement the chroma key effect, follow these steps:

  1. Select the VideoStreamPlayer node in the scene and go to its properties. Under CanvasItem > Material, create a new shader named "ChromaKeyShader.gdshader."

  2. In the "ChromaKeyShader.gdshader" file, write the custom shader code as shown below:

shader_type canvas_item;

// Uniform variables for chroma key effect
uniform vec3 chroma_key_color : source_color = vec3(0.0, 1.0, 0.0);
uniform float pickup_range : hint_range(0.0, 1.0) = 0.1;
uniform float fade_amount : hint_range(0.0, 1.0) = 0.1;

void fragment() {
    // Get the color from the texture at the given UV coordinates
    vec4 color = texture(TEXTURE, UV);

    // Calculate the distance between the current color and the chroma key color
    float distance = length(color.rgb - chroma_key_color);

    // If the distance is within the pickup range, discard the pixel
    // the lesser the distance more likely the colors are
    if (distance <= pickup_range) {
        discard;
    }

    // Calculate the fade factor based on the pickup range and fade amount
    float fade_factor = smoothstep(pickup_range, pickup_range + fade_amount, distance);

    // Set the output color with the original RGB values and the calculated fade factor
    COLOR = vec4(color.rgb, fade_factor);
}

The shader uses the distance calculation to identify pixels close to the chroma key color and discards them, effectively removing the selected color. Pixels that are slightly further away from the chroma key color are faded based on the fade_factor, blending them smoothly with the surrounding colors. This process creates the desired chroma key effect, making it appear as if the background has been replaced with another image or video.

The code above represents a simple demonstration of the Chroma Key shader, and users can customize it according to their specific requirements.

UI Controls

To allow users to manipulate the chroma key effect in real-time, we created sliders in the Control node. The Control node's script contains the following functions:

 extends Control

 func _on_color_picker_button_color_changed(color):
     # Update the "chroma_key_color" shader parameter of the VideoStreamPlayer's material.
     $VideoStreamPlayer.material.set("shader_parameter/chroma_key_color", color)

 func _on_h_slider_value_changed(value):
     # Update the "pickup_range" shader parameter of the VideoStreamPlayer's material.
     $VideoStreamPlayer.material.set("shader_parameter/pickup_range", value)

 func _on_h_slider_2_value_changed(value):
     # Update the "fade_amount" shader parameter of the VideoStreamPlayer's material.
     $VideoStreamPlayer.material.set("shader_parameter/fade_amount", value)

func _on_video_stream_player_finished():
     # Restart the video playback when it's finished.
     $VideoStreamPlayer.play()

also make sure that the range of the sliders are appropriate, our settings are :

../../_images/slider_range.webp

Signal Handling

Connect the appropriate signal from the UI elements to the Control node's script. you created in the Control node's script to control the chroma key effect. These signal handlers will update the shader's uniform variables in response to user input.

Save and run the scene to see the chroma key effect in action! With the provided UI controls, you can now adjust the chroma key color, pickup range, and fade amount in real-time, achieving the desired chroma key functionality for your video content.