How does one embed the audio portion of any YouTube video into your website? a simple option would be that you simply convert the YouTube video into an MP3 file and upload it to an audio hosting website like Soundcloud. this may work however YouTube is very likely to own a problem with your approach because of copyright problems.

There’s an easier approach as well that uses the official YouTube API and needs no file conversion.

You can embed any YouTube video in your web pages and visitors on your website will be able to play and pause the video audio with an easy click. With this technique, you’ll also use a YouTube video as background audio that runs in a loop.

It should resemble an embedded audio player however there’s actually this YouTube video that’s playing in the background.

How to Embed YouTube as an Audio Player

How to Embed YouTube Audio

It takes only one step to embed a YouTube audio. Open any YouTube video and create a note of the YouTube Video ID (a string of 11 characters).

Next copy-paste the code below anyplace on your website and replace VIDEO_ID with actual ID of your YouTube video.

<div data-video="VIDEO_ID"
data-autoplay="0"
data-loop="1"
id="youtube-audio">
</div>
<script src="https://www.youtube.com/iframe_api"></script>
<script src="http://www.lifenan.com/master/js/yt.js"></script>

There are few different configuration parameters that you just will change depending on requirements. for instance, if you set data-autoplay to one, the audio can begin playing immediately on page load. Likewise, set data-loop to 1 and the audio can play continuously in a never-ending loop till manually stopped.

This internally renders the YouTube video using the IFRAME player and would therefore work on each desktop and mobile browsers.

The JavaScript files are hosted on Github while the pictures are hosted on Imgur. it’s recommended that you just copy the assets to your own server before deploying on a heavy-traffic website.

YouTube Audio – The Technical Details

We are using the YouTube JavaScript API that renders a regular YouTube player however with the width and height set to zero pixels. once the user clicks the audio button, it toggles the existing YouTube player state and the video begins to play or pauses.

It may be extended to embed YouTube playlists, the default playback volume may be modified otherwise you even embed a part of the video.