I play with <audio>
tag to play mp3 file handy and portably.
This simplest audio player has no special feature, just plays an audio file!
You can use it like below.
<audio src="/yourfile.mp3" controls></audio>
DONE!
...oh, This doesn't looks convenient so much.
At the least, I want to choose a file. HOW?
<audio>
detects the file to play from src
attribute.
So, All I need are preparing file choose and creating <audio>
DOM.
Maybe it needs a little state managing.
- No file to play: Only
<input type="file">
is enabled - There is a file to play:
<audio>
is enabled
I decided to use mithriljs to control states because this is declarative, easy and compile free.
Implementing looks like below. (details are omitted.)
// The global model to manage state. const model = { fileObj: null, blobUrl: null, }; function handleFile(e) { // create blob URL. model.fileObj = e.target.files[0]; model.blobUrl = URL.createObjectURL(model.fileObj); } // The component to choose file. const itemComponent = { view() { return m('input', {type: "file", onclick: handleFile }); }, }; // The component rendering <audio> DOM. const audioComponent = { view() { return m('audio', { controls: true, src: model.blobUrl }); }, }; // Entrypoint const app = { view() { // This draws <audio> DOM after chosen file. return m(model.fileObj ? audioComponent : itemComponent); } };
Actual implementing has file drop and restore playing posigion, but essentials are just these. (please see: https://js.do/code/451129)
Top comments (0)