31. Audio, Video and iframes (<video>, <audio>, <iframe>)
Embedding songs, movies and YouTube videos on a website
Real-life analogy
Before HTML5, playing video needed third-party apps like the Flash player. Now HTML5 has a built-in TV screen!
Explanation
1. HTML Video & Audio:
<video controls>: To play a video with play/pause buttons.<audio controls>: To play audio.- Attributes:
autoplay,loop,muted,poster="thumb.jpg".
2. YouTube Embedding: With the <iframe> tag you can embed YouTube videos without putting any load on your server.
Golden rules
- Be sure to add the
controlsattribute on video and audio tags, otherwise the user will not see the play/pause button. - If you want to
autoplaya video, it is also necessary to addmutedalong with it.
Common mistake
Forgetting to write controls, so the video appears on screen but there is no button to start it.
Example code
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; padding: 20px;">
<h4 style="margin-top: 0;">1. Audio Player (<audio controls>):</h4>
<audio controls style="width: 100%; max-width: 280px;">
<source src="https://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
Your browser does not support audio.
</audio>
<h4 style="margin-top: 15px;">2. YouTube Video (Iframe Embed):</h4>
<iframe width="100%" height="160" style="max-width: 280px; border-radius: 6px;"
src="https://www.youtube.com/embed/dQw4w9WgXcQ"
frameborder="0" allowfullscreen>
</iframe>
</body>
</html>
Quick quiz
Which attribute has to be added to a video tag to show play, pause and volume slider?
- buttons
- player
- controls
- playbar
Show answer
Answer: controls
The controls attribute gives the user play, pause and volume controls.