Jukebox RSS player in SVG

Yes I'm back on my daftness.

With help from Tabs aka LadyOfCode and her chat/ Discord channel, I've been making adjustments to my home page. Some simple things like adding padding and changing the menu, to a large one that was the landing page was uninspiring. I'd minimised it to a quick blurb and links to things, but Tabs suggested I put more on the book and podcast on that page, as this is about me and those are things I'm very proud of. So I added more information on my book and Copperheart but wanted something needlessly complicated and unneccessary. Because being a Steampunk mad scientist means never stopping to contemplate Why Do This, as long as I can figure out How.

I'd wanted to make a Podcast player for a while. Why not jazz it up for the Copperheart section as a ye-olde radio?

HTML Components

Out of the box I wanted to use HTML components, as that's native and supported by the browser rather than me. For a podcast I needed (1) an audio object for the playing of audio, and (2) a select object for the selection of audio. Luckilly both those elements already exist.

1<audio controls="true"><source src="..." type="..."></audio>
2<select>...</select>

Audio is really easy to use, throw the URL of the audio into the src tag and the media type into the type tag, and away you go. Select is similarly easy to use, populate the select with the options you want, and huzzah. First trick, though - pull in the RSS feed

Javascript 1 - reading RSS feed.

A quick DuckDuckGo found How To Fetch And Parse RSS Feeds in Javascript which used all natural ingredients. The RSS feed for Copperheart contains the media URL and the media Type, both of which were easy to plumb into the select box. Adding an onchange event and I updated the Audio based on what was selected.

Quality of life changes: Defaulting the audio on first load to the latest podcast.

 1fetch("https://feeds.libsyn.com/174362/rss")
 2    // Get and parse the result
 3    .then(response => response.text())
 4    .then(str => new window.DOMParser().parseFromString(str, "text/xml"))
 5    .then(data => {
 6        // Get each <item> element, initialise target
 7        const items = data.querySelectorAll("item");
 8        const target = document.getElementById("podcast-episodes")
 9        target.innerHTML = "";
10        // Create an add an option for each found episode
11        items.forEach(el => { 
12            let opt = document.createElement("OPTION")
13            opt.innerText = el.querySelector("title").innerHTML;
14            opt.value = el.querySelector("enclosure").getAttribute("url")
15            opt.setAttribute("data-type", el.querySelector("enclosure").getAttribute("type"));
16            // Using Prepend to reverse order, so first is at the top
17            target.prepend(opt); 
18        });
19        // When someone changes the select box, update the audio object
20        target.onchange = (e) => { 
21            e.preventDefault();
22            let selected_option = e.target.options[e.target.selectedIndex];
23            let target_audio = document.querySelector("audio")
24            let target_src = document.querySelector("audio source")
25            target_src.setAttribute('src', e.target.value);
26            target_src.setAttribute('type', selected_option.getAttribute("data-type"));
27            // Gotcha: if you don't load() the audio, nothing happens
28            target_audio.load(); 
29        }
30        // Default the audio on load to the latest episode
31        target.value = target.querySelector("option:last-child").value;
32        target.querySelector("option:last-child").selected = true;            
33        document.querySelector("#podcast-player source").setAttribute("src", target.value);  
34        document.querySelector("#podcast-player source").setAttribute("type",  target.querySelector("option:last-child").getAttribute("data-type"));
35        document.querySelector("audio").load(); 
36    });

This results in... well a functional if uninspiring podcast listener.

Basic

SVG

Maths. If you don't love it... you won't love this section.

I looked up a bunch of inspiration for olde style radioes. There are a lot. The one I found the best image for was a radio on Amazon. Nice wood, interesting patterns. Time to start svging.

Step 1 - Basic outlines.

I create basic objects for each shape. Arc for the top, two columns for the sides, arched top bit for the middle, and rectangles-with-wiggles for the bottom and decorative bits. I'm not looking at the speaker yet. Each object has a colour so I can tell them apart.

Colour Outlines

Gotcha: I used stroke-width: 3px when drawing outlines to make it easier to spot. This, however, threw all my calculations out by 3 once I removed the stroke. Relative units are your friend.

Step 2 - Side columns

Patterns in SVG are can be simple repeating drawings, like having a 5r circle filling your object. The columns were a repeating pattern right to left of light and dark wood colours. I figured using the alpha channel to provide different shading of the verticals would work, and it did. Once they were in place, I also added a highlight line and a shadow line to give it more depth.

I took that logic to add a shader bar to the edge of each column to give it more shape.

 1<pattern id="side-columns" patternUnits="userSpaceOnUse" x="0" y="0" width="25" height="30" viewBox="0 0 25 30">
 2    <rect x="0" y="0" stroke-width="0" height="30" width="25" fill="brown"></rect>
 3    <rect x="0" y="0" stroke-width="0" height="30" width="12.5" fill="rgba(0,0,0,0.0)"></rect>
 4    <rect stroke-width="0" y="0" height="30" x="12.5" width="12.5" fill="rgba(0,0,0,0.2)"></rect>
 5    <line x1="0" y1="0" x2="0" y2="30" stroke-width="1" stroke="rgba(255,255,255,0.3)"></line>
 6    <line y1="0" stroke-width="1" stroke="rgba(0,0,0,0.3)" y2="30" x1="12.5" x2="12.50"></line>
 7</pattern>
 8
 9<path stroke-width="3px" d="M150 332 l 0 471 l -107 0 l0 -471 Z" stroke="blue" fill="url(#side-columns)"></path>
10<path stroke-width="3px" d="M630 332 l 0 471 l 107 0 l0 -471 Z" stroke="blue" fill="url(#side-columns)"></path>

Sidebars

Step 3 - Wood grain

I found an excellent noise tutorial and used that as a shading layer to make a darker wood grain. I ended up using the wood grain for the top and middle sections, as well as replacing brown in the side bars.

1<pattern id="top-section" patternUnits="userSpaceOnUse" x="0" y="0" width="900" height="500" viewBox="0 0 900 500">
2    <filter id="filter">
3        <feTurbulence type="fractalNoise" baseFrequency=".1 .01"></feTurbulence>
4        <feColorMatrix values="0.2 0.2 0 .11 .69 0 0.2 0 .09 .38 0.2 0 0.2 .08 .14 0 0 0 0.2 1"></feColorMatrix>
5    </filter>
6    <rect width="100%" height="100%" fill="rgba(140,22,15)"></rect>
7    <rect width="100%" height="100%" filter="rgb(0,0,0)" opacity="0.6"></rect>
8    <rect width="100%" height="100%" filter="url(#filter)" opacity="0.3"></rect>
9</pattern>

Wood Grain

Step 4 - Curved wood shading

Looking at the example picture, this area is the most complex. Somehow I had to turn the curved ends to make it look like light/ shadow interplay over concave and convex surfaces. I'm not sure if this was the best approach, but I went for a gradient.

A gradient is a fill-type where you can specify colours at points on a spectrum, and the browser tries to blend each colour transformation together smoothly. I started with a basic darker colour and played with gradient stop-points to get a lighter shading on the "top" of bulges and darker shading on the "inset" of the bulges. And, after an hour of playing, it did the job. Once again, I stacked the layer on top of the wood grain for consistency of colours.

 1<pattern id="vertical-gradient" patternUnits="userSpaceOnUse" x="0" y="0" width="2" height="32" viewBox="0 0 2 32">
 2    <linearGradient id="lG" x1="50%" y1="0" x2="50%" y2="100%">
 3        <stop stop-color="rgba(0,0,0,0.6)" offset="0%"></stop>
 4        <stop stop-color="rgba(255,255,255,0.8)" offset="8%"></stop>
 5        <stop stop-color="rgba(0,0,0,0.6)" offset="12%"></stop>
 6        <stop stop-color="rgba(0,0,0,0.3)" offset="38%"></stop>
 7        <stop stop-color="rgba(0,0,0,0.6)" offset="40%"></stop>
 8        <stop stop-color="rgba(255,255,255,0.5)" offset="40%"></stop>
 9        <stop stop-color="rgba(0,0,0,0.6)" offset="70%"></stop>
10        <stop stop-color="rgba(255,255,255,0.2)" offset="90%"></stop>
11    </linearGradient>
12    <rect x="0" y="0" stroke-width="0" height="32" width="2" fill="url(#top-section)"></rect>
13    <rect x="0" y="0" stroke-width="0" height="32" width="2" fill="url(#lG)"></rect>
14</pattern>

Gotcha: The gradient seemed to start at ... odd places. I really had to fiddle to find out where the wrap occured. If you've got ideas, ping me.

Gradient

Step 5 - Speaker

I have the pattern for the speaker from Philip Rogers' SVGPatterns gallery. I hadn't sketched out the position for the speakers like I had the earlier code, but I just ended up winging it anyway by taking the arc for the front section, moving it down and shrinking it, and playing around with creating a decorative wavy section at the bottom. The idea of trying to make all the cutouts was far too tiring for me by this point.

Note that I added a opacity border to this to give it an inset effect that worked like a charm.

1<pattern xmlns="http://www.w3.org/2000/svg" id="speakers" patternUnits="userSpaceOnUse" x="0" y="0" width="15" height="15" viewBox="0 0 15 15">
2            <rect width="50" height="50" fill="BurlyWood"/>
3            <circle cx="3" cy="4.3" r="1.8" fill="#393939"/>
4            <circle cx="3" cy="3" r="1.8" fill="black"/>
5            <circle cx="10.5" cy="12.5" r="1.8" fill="#393943"/>
6            <circle cx="10.5" cy="11.3" r="1.8" fill="black"/>
7        </pattern>
8
9<path xmlns="http://www.w3.org/2000/svg" id="speakers" fill="url(#speakers)" stroke-width="5px" d="M191 318 A 200 150 1 0 1 599 318 l 0 200 A 50 45 1 0 1 491 518 A 50 50 1 0 0 291 519 A 50 45 1 0 1 191 519 Z" stroke="rgba(33,33,33,0.5)"/>

Speakers

Embedded image

I had my speaker, I had my controls. Combining the two was the factor of adding a div and setting the SVG as the background image, then position:absolute positioning the controls where I wanted them.

1<section id="podcast-player" style="width: 400px; height: 440px; background-image: url(&quot;/theme/images/radio.svg&quot;); background-size: 400px 620px; background-position: 0px -90px; background-repeat: repeat; position: relative;"><div style="position: absolute; bottom: 80px; text-align: center; width: 100%;"><audio controls="true"><source></audio></div><div style="position: absolute; bottom: 60px; text-align: center; width: 100%;"><select style="text-align: center;" id="podcast-episodes">...</select></div></section>

Version 1

Javascript

Since this only works with Javascript enabled (to pull down the RSS feed), I converted all the HTML into a Javascript build that I won't post in here. Suffice to say, it only shows on the page if you've got JavaScript enabled so it'll work

Bonus round - Volume control.

There was a space in the middle of the speaker I knew I wanted to do something with. The basic control already had a scroble. So.. volume control?

I then went down a fruitless rabbit warren of trying to figure out how to curve an element. You can curve text on a textPath in svg, but not a foriegn element or similar. Since this whole thing is JavaScript dependant anyway, I felt less bad about making volume control a purely graphical element - especially given there are other controls that let you change volume at your disposal.

Circle and visual control

First I made a circle for the dial using the basic circle element. This I then used as the baseline for an arc that wasn't a full circle, miraculously guessing the start and end points on the circle. I added a knob to show where on the arc it was, and a knob in the centre for aesthetics.

Javascript - where is the interaction?

Then I had to add the events to capture the interaction on the knob. It's not dragging it, so its not an ondrag, it's a combination of mousein/mousedown/mouseout touchstart/touchmove/touchcancel. I set a flag to record if the interaction has started/ is still going and only calculate move events if that's the case. Move is all relative to the middle dot, so high school calculus and arctangents to the rescue.

That and a LOT of fiddling of numbers to figure out where the arcs are coming from. Like a lot. What's the deal with some JS angles being degrees and some radians?

It also sets the volume on load, and tracks the other volume knob to set them to equal values.

 1// Maximum rotation is 310 degrees
 2const mainbox = document.getElementById("volume-knob"),
 3    volumeDot = document.getElementById("volume-dot");
 4var volumeAdjusting = false,
 5    volumeMousePlace = [0,0];
 6
 7// On interact, record we're adjusting and update slider
 8mainbox.addEventListener('mousedown', (e) => {
 9    volumeAdjusting = true;
10    volumeMousePlace = getRelativeMousePosition(e.clientX, e.clientY);
11    adjustSlider();
12});
13// Stop updating slider
14mainbox.addEventListener('mouseup', (e) => {
15    volumeAdjusting = false;
16});
17mainbox.addEventListener('mouseout', (e) => {
18    volumeAdjusting = false;
19});
20// If we're adjusting, update slider
21mainbox.addEventListener('mousemove', (e) => {
22    if (volumeAdjusting) {
23        volumeMousePlace = getRelativeMousePosition(e.clientX, e.clientY);
24        window.console.log("Base place " + volumeMousePlace[0] + "," + volumeMousePlace[1]);
25        adjustSlider();
26    }
27});
28
29function getRelativeMousePosition(x, y) {
30    let masterPosition = document.getElementById("volume-knob").getBoundingClientRect(),
31        masterX = masterPosition.x,
32        masterY = masterPosition.y;
33    return [x - masterX, y - masterY];
34}
35
36function adjustSlider() {
37    let dangle = getAngle();
38    volumeDot.setAttribute(
39        "transform",
40        `rotate(${dangle},50,50)`);
41    document.querySelector("audio").volume = dangle / 310;
42}
43
44// This spins the knob selector around its centre point based on where the
45// interaction is relative to the knob centre, based on the `<audio>` volume
46function adjustKnob() {
47    volumeDot.setAttribute(
48        "transform",
49        `rotate(${document.querySelector("audio").volume}, 50, 50)`
50    )
51}
52adjustKnob();
53document.querySelector("audio").addEventListener("volumechange", adjustKnob, false);
54
55// Here's that ArcTan to convert the x,y interaction position to an angle
56// that then can be applied elsewhere
57function getAngle() {
58    window.console.log(volumeMousePlace);
59    // Adjust X/Y for correct angle calculation
60    let opposite = (48 - volumeMousePlace[1]),
61        adjacent = (48 - volumeMousePlace[0]),
62        rangle = Math.atan(opposite/adjacent),
63        dangle = radiansToDegrees(rangle) + 53 // Start angle;
64    if (volumeMousePlace[0] > 48) {
65        dangle = dangle + 180;
66    }
67    if (dangle < 0) {
68        dangle = 0;
69    }
70    if (dangle > 305) {
71        dangle = 310
72    }
73    return dangle;
74}
75
76function radiansToDegrees(radians) {
77    return radians * (180 / Math.PI);
78}

Conclusion

It was a brilliantly fun day and a bit of hacking while very, VERY sick. Four rapid antigen tests over a week to ensure I wasn't going to covid the family but... man. That could be why I enjoyed the distraction on such a patently ridiculous thing, but it actually works and I really like it.