AudioPlayer
An instance of AudioPlayer can play an audio from a server, load an audio from a file on the the local disk an play it, record an audio with a microphone and play it, send a loaded or a recorded audio file to a server, delete an audio file from a server. All functionalities are optional.
REMINDER: The layout and the style of an interface are in the hands of the programmer. No graphical design is imposed. Coding the look of an instance of AudioPlayer is done instantly. The examples on this page use the icons from Font Awesome.
Coordinating an audio player with a playlist managed by an instance of a AudioPlaylist takes just a few lines of code.
- Responder
- View
- AudioPlayer
- View
Press the play button to start playing the audio. Press the pause button to pause it. Move the slider or click in the progression bar to jump forward or backward in the audio. Turn on or off playing the audio in a loop.
Click on the load button to load an audio file from the local disk. Select a MP3, OGG or WAV file. NOTE: The maximum size of the file is configured to 10 MB. Open a folder containing audios with the explorer of your file system. Drag and drop a MP3, OGG or WAV file over the player. NOTE: Reading AAC and AC3 files is hazardous. Try to read a WEBM and different video containers.
Click on the microphone to start recording an audio. Click on the open microphone to stop the recording.
Once you have loaded or recorded an audio, you can click on the upload button to send the file to the server. The file is transferred in 100 kB blocks. The progression is displayed by a percentage. In case of error, the upload button turns red. NOTE: On this server, you can only save MP3 or OGG files.
Click on the trash can to delete the file on the server. If the server returns an error, the trash can turns red.
NOTE: In the example implementation, writing data and destroying the file are simulated by the server.
To start loading an audio from a file with a button, a code can run the method loadAudio
of the player when the button is clicked.
IMPORTANT: For security reasons, loadAudio
must be called in response to a user interaction.
- <p class="noprint"><button id="btn_load_audio" type="submit" class="narrow" title=""><i class="fa fa-file-audio"></i></button></p>
- <script>
- document.getElementById('btn_load_audio').onclick = () => audioplayer.loadAudio();
- </script>
In the console of the browser, display the duration of the audio:
audioplayer.duration
Change the audio in the player:
audioplayer.src='/files/sounds/smoke.ogg'
or
audioplayer.src='/files/sounds/smoke.mp3'
Start playing the audio:
audioplayer.play()
Pause it:
audioplayer.pause()
Destroy the interface:
audioplayer.destroyWidget()
Restart the audio:
audioplayer.replay()
Create and show the interface then reset it:
audioplayer.createManagedWidget().resetWidget()
- function AudioPlayer(options = false) {
- const audio = new Audio();
- if (! (audio.canPlayType('audio/ogg') || audio.canPlayType('audio/mpeg')) )
- throw new TypeError();
- this._audio = audio;
- options = options || {};
- let recorder = options.recorder ? true : false;
- let load = options.load ? true : false;
- let draganddrop = options.draganddrop ? true : false;
- let deleteURL = options.deleteURL;
- let uploadURL = options.uploadURL;
- if (! (typeof deleteURL === 'undefined' || deleteURL === null || typeof deleteURL === 'string'))
- throw new TypeError();
- if (! (typeof uploadURL === 'undefined' || uploadURL === null || typeof uploadURL === 'string'))
- throw new TypeError();
- if (! (recorder || load || draganddrop))
- uploadURL = null;
- if (uploadURL) {
- let chunksize = options.chunksize;
- if (chunksize === undefined)
- chunksize = 100000;
- else if (!Number.isInteger(chunksize))
- throw new TypeError();
- else if (chunksize < 10000)
- throw new RangeError();
- this._chunksize = chunksize;
- let maxfilesize = options.maxfilesize;
- if (maxfilesize === undefined)
- maxfilesize = 1000000;
- else if (!Number.isInteger(maxfilesize))
- throw new TypeError();
- else if (maxfilesize < 100000)
- throw new RangeError();
- this._maxfilesize = maxfilesize;
- }
- View.call(this);
- if (recorder) {
- if (MediaRecorder.isTypeSupported('audio/ogg'))
- this._mediatype = 'audio/ogg';
- else if (MediaRecorder.isTypeSupported('audio/mpeg'))
- this._mediatype = 'audio/mpeg';
- else if (MediaRecorder.isTypeSupported('audio/webm'))
- this._mediatype = 'audio/webm';
- else
- this._mediatype = null;
- recorder = this._mediatype ? true : false;
- }
- this._recorder = recorder;
- this._mediarecorder = null;
- this._mediablob = null;
- this._load = load;
- this._draganddrop = draganddrop;
- this._deleteURL = deleteURL;
- this._uploadURL = uploadURL;
- this._playWidget = null;
- this._pauseWidget = null;
- this._barWidget = null;
- this._timeWidget = null;
- this._loopWidget = null;
- this._loadWidget = null;
- this._fileWidget = null;
- this._deleteWidget = null;
- this._uploadWidget = null;
- this._statusWidget = null;
- this._recordStartWidget = null;
- this._recordStopWidget = null;
- this._seeking = false;
- this._uploading = false;
The AudioPlayer class inherits from the View class.
The parameter options
of the constructor is an object which configures the options recorder
, load
, dragandrop
, deleteURL
, uploadURL
and chunksize
.
If recorder
is true
, the instance accepts to manage the recording of an audio with the microphone of the browser.
If load
is true
, the instance accepts to load an audio file from the local disk in response to a user interaction.
If draganddrop
is true
, the instance accepts to load an audio file that the user has dropped on the interface.
deleteURL
is a character string which specifies the URL of the POST sent to the server to delete an audio.
uploadURL
is a character string which specifies the URL of the POST sent to the server to upload an audio.
chunksize
specifies the size of the data blocks sent to the server, 100 kB by default.
If the browser cannot play an audio of type audio/ogg or audio/mpeg, the constructor throws an error TypeError.
If one the the options recorder
, load
or dragandrop
isn't true
, the instance will never be able to upload an audio and the option uploadURL
is set to false
.
If chunksize
is defined and is not an integer, the constructor throws an error TypeError. If chunksize
is a number less than 10000, the constructor throws an error RangeError.
if recorder
is true
, the constructor checks if the browser can record an audio with the format audio/ogg, audio/mpeg or audio/webm and memorizes it. Otherwise, the option recorder
is set to false
.
NOTE;: The recorder is created in response to the first request for a recording.
- this._uploadable = false;
- this._autoplay = false;
- this._error = null;
duration
is an accessor which returns the duration in milliseconds of the audio of this
, 0 by default.
- AudioPlayer.prototype = Object.create(View.prototype);
- Object.defineProperty(AudioPlayer.prototype, 'constructor', { value: AudioPlayer, enumerable: false, writable: true });
- Object.defineProperty(AudioPlayer.prototype, 'duration', {
- get: function() {
- return this._audio.src ? Math.floor(this._audio.duration * 1000) : 0;
- }
- });
- Object.defineProperty(AudioPlayer.prototype, 'currentTime', {
- get: function() {
- return this._audio.src ? Math.floor(this._audio.currentTime * 1000) : 0;
currentTime
is an accessor which returns or sets the current position in milliseconds of the audio of this
.
If this
is recording or uploading the audio, changing the position of the audio is ignored.
- set: function(ms) {
- if (this._recording || this._uploading)
- return;
- if (!this._audio.src)
- return;
- this._audio.currentTime = ms / 1000;
- }
- });
- Object.defineProperty(AudioPlayer.prototype, 'src', {
- get: function() {
- return this._audio.src;
- },
- set: function(url) {
- if (this._recording || this._uploading)
- return;
- this._autoplay = this.playing && url;
- if (this._audio.src)
- URL.revokeObjectURL(this._audio.src);
- if (url)
- this._audio.src = url;
- else {
- this._audio.removeAttribute('src');
src
is an accessor which returns or sets the URL of the audio of this
.
If this
is recording or uploading the audio, changing the URL of the audio is ignored.
- this._showDuration();
- }
- this._mediablob = null;
- this._uploadable = false;
- this._error = null;
- }
- });
- Object.defineProperty(AudioPlayer.prototype, 'loop', {
- get: function() {
- return this._audio.loop;
- },
- this._audio.loop = flag ? true : false;
- if (this._loopWidget) {
- if (this._audio.loop)
- this._loopWidget.classList.remove('off');
- this._loopWidget.classList.add('off');
- }
- }
- });
- get: function() {
- return this._audio.src && !this._audio.paused;
- }
- });
- Object.defineProperty(AudioPlayer.prototype, 'recording', {
- get: function() {
- return this._mediarecorder && this._mediarecorder.state !== 'inactive';
- }
- });
- AudioPlayer.prototype.setFromTracks = function(soundtracks) {
- let url = null;
- if (soundtracks) {
- if ('audio/wav' in soundtracks && this._audio.canPlayType('audio/wav')) {
- url = soundtracks['audio/wav'];
- }
- else if ('audio/ogg' in soundtracks && this._audio.canPlayType('audio/ogg')) {
- url = soundtracks['audio/ogg'];
- else if ('audio/mpeg' in soundtracks && this._audio.canPlayType('audio/mpeg')) {
- url = soundtracks['audio/mpeg'];
- }
- else if ('audio/webm' in soundtracks && this._audio.canPlayType('audio/webm')) {
- url = soundtracks['audio/webm'];
- }
- }
- return this.src = url;
- };
- if (w.tagName != 'AUDIO')
- throw new TypeError();
- for (let source of w.querySelectorAll('source'))
- soundtracks[source.getAttribute('type')] = source.getAttribute('src');
- return this.setFromTracks(soundtracks);
- };
- AudioPlayer.prototype.canPlayType = function(type) {
- return this._audio.canPlayType(type) ? true : false;
- };
- if (!this._audio.src)
- return this;
- if (this._recording)
- return this;
- this._audio.play();
- return this;
- };
- if (!this._audio.src)
- return this;
- if (this._recording)
- return this;
- this._audio.pause();
- return this;
- };
- AudioPlayer.prototype.replay = function() {
- if (!this._audio.src)
- if (this._recording)
- return this;
- this._audio.currentTime = 0;
- this._audio.play();
- return this;
- };
- AudioPlayer.prototype.resetWidget = function() {
- if (this._playWidget && this._pauseWidget) {
- if (!this._audio.src || this._recording) {
- this._playWidget.classList.add('disabled');
- this._pauseWidget.classList.add('disabled');
- }
- else {
- this._playWidget.classList.remove('disabled');
- this._pauseWidget.classList.remove('disabled');
- }
- }
- if (this._barWidget ) {
- if (!this._audio.src || this._recording)
- this._barWidget.disabled = true;
- else
- this._barWidget.disabled = false;
- }
- if (this._loopWidget ) {
- if (this._audio.loop)
- this._loopWidget.classList.remove('off');
- else
- this._loopWidget.classList.add('off');
- }
- if (this._uploadWidget) {
- if (this._uploadable && !this._uploading && !this._recording)
- this._uploadWidget.classList.remove('disabled');
- else
- this._uploadWidget.classList.add('disabled');
- if (this._error == 'upload')
- this._uploadWidget.classList.add('inerror');
- else
- this._uploadWidget.classList.remove('inerror');
- }
- if (this._deleteWidget) {
- if (this._deletable && !this._uploading)
- this._deleteWidget.classList.remove('disabled');
- else
- this._deleteWidget.classList.add('disabled');
- if (this._error == 'delete')
- this._deleteWidget.classList.add('inerror');
- else
- this._deleteWidget.classList.remove('inerror');
- }
- if (this._recordStartWidget && this._recordStopWidget) {
- if (!this._recorder || this._uploading) {
- this._recordStartWidget.classList.add('disabled');
- this._recordStopWidget.classList.add('disabled');
- }
- else {
- this._recordStartWidget.classList.remove('disabled');
- this._recordStopWidget.classList.remove('disabled');
- if (this._error == 'record')
- this._recordStartWidget.classList.add('inerror');
- else
- this._recordStartWidget.classList.remove('inerror');
- }
- }
- if (this._loadWidget) {
- if (this._recording || this._uploading)
- this._loadWidget.classList.add('disabled');
- this._loadWidget.classList.remove('disabled');
- if (this._error == 'load')
- this._loadWidget.classList.add('inerror');
- else
- this._loadWidget.classList.remove('inerror');
- }
- return this;
- };
- AudioPlayer.prototype.setWidget = function(w) {
- View.prototype.setWidget.call(this, w);
- this._playWidget = w.querySelector('.audioplay');
- this._pauseWidget = w.querySelector('.audiopause');
- this._loopWidget = w.querySelector('.audioloop');
- this._timeWidget = w.querySelector('.audiotime');
- this._barWidget = w.querySelector('.audiobar');
- if (this._barWidget && this._barWidget.tagName != 'INPUT')
- this._barWidget = null;
- this._recordStartWidget = w.querySelector('.recordstart');
- this._recordStopWidget = w.querySelector('.recordstop');
- this._loadWidget = w.querySelector('.fileload');
- this._fileWidget = w.querySelector('.mediafile');
- if (this._fileWidget && this._fileWidget.tagName != 'INPUT')
- this._fileWidget = null;
- this._deleteWidget = w.querySelector('.audiodelete');
- this._uploadWidget = w.querySelector('.audioupload');
- this._statusWidget = w.querySelector('.mediastatus');
- const playing = this._audio.src && !this._audio.paused;
- const recording = this._mediarecorder && this._mediarecorder.state !== 'inactive';
- if (this._playWidget) {
- this._playWidget.hidden = playing ? true : false;
- this._playWidget.addEventListener('click', () => {
- if (!this._playWidget.classList.contains('disabled'))
- this.play();
- });
- }
- if (this._pauseWidget) {
- this._pauseWidget.hidden = playing ? false : true;
- this._pauseWidget.addEventListener('click', () => {
- if (!this._pauseWidget.classList.contains('disabled'))
- this.pause();
- });
- }
- if (this._loopWidget) {
- this._loopWidget.addEventListener('click', () => {
- if (!this._loopWidget.classList.contains('disabled'))
- this.loop = !this.loop;
- });
- }
- if (this._barWidget) {
- if (!playing) {
- this._barWidget.value = (this._audio.currentTime ? Math.floor(this._audio.currentTime / this._audio.duration * 100) : 0);
- this._showCurrentTime();
- }
- this._barWidget.addEventListener('mousedown', () => this._seeking = true);
- this._barWidget.addEventListener('mouseup', () => this._seeking = false);
- this._barWidget.addEventListener('change', () => {
- const duration = this._audio.src ? this._audio.duration : 0;
- if (duration) {
- let secs = this._barWidget.value / 100 * duration;
- secs = secs < this._audio.currentTime ? Math.floor(secs) : Math.ceil(secs);
- this._audio.currentTime = this._audio.loop && secs >= duration ? 0 : secs;
- }
- });
- }
- if (this._draganddrop) {
- w.addEventListener('drop', (e) => {
- const dt = e.dataTransfer;
- e.preventDefault();
- if (dt.types.indexOf('Files') != -1) {
- this._loadFile(dt.files[0]);
- }
- });
- w.addEventListener('dragenter', (e) => {
- const dt = e.dataTransfer;
- if (dt.types.indexOf('Files') != -1) {
- e.preventDefault();
- }
- });
- w.addEventListener('dragleave', (e) => {
- e.preventDefault();
- });
- w.addEventListener('dragover', (e) => {
- const dt = e.dataTransfer;
- e.preventDefault();
- dt.dropEffect = dt.types.indexOf('Files') != -1 && !(this._recording || this._uploading) ? 'copy' : 'none';
- });
- }
- if (this._fileWidget)
- this._fileWidget.hidden = true;
- if (this._loadWidget) {
- this._loadWidget.classList.add('disabled');
- if (this._fileWidget) {
- if (this._load) {
- this._loadWidget.addEventListener('click', () => {
- if (!this._loadWidget.classList.contains('disabled') && !(this._recording || this._uploading))
- this._fileWidget.click();
- });
- this._fileWidget.addEventListener('change', (e) => {
- if (e.target.value) {
- this._loadFile(e.target.files[0]);
- }
- });
- }
- }
- else
- this._loadWidget = null;
- }
- if (this._recordStartWidget) {
- this._recordStartWidget.classList.add('disabled');
- this._recordStartWidget.hidden = recording ? true : false;
- if (this._recorder) {
- this._recordStartWidget.addEventListener('click', () => {
- if (!this._recordStartWidget.classList.contains('disabled'))
- this.recordStart();
- });
- }
- else
- this._recordStartWidget = null;
- }
- if (this._recordStopWidget) {
- this._recordStopWidget.hidden = recording ? false : true;
- if (this._recorder) {
- this._recordStopWidget.addEventListener('click', () => {
- if (!this._recordStopWidget.classList.contains('disabled'))
- this.recordStop();
- });
- }
- else
- this._recordStopWidget = null;
- }
- if (this._uploadWidget) {
- this._uploadWidget.classList.add('disabled');
- if (this._uploadURL) {
- this._uploadWidget.addEventListener('click', () => {
- if (!this._uploadWidget.classList.contains('disabled'))
- this.uploadFile();
- });
- }
- else
- this._uploadWidget = null;
- }
- if (this._deleteWidget) {
- this._deleteWidget.classList.add('disabled');
- if (this._deleteURL) {
- this._deleteWidget.addEventListener('click', () => {
- if (!this._deleteWidget.classList.contains('disabled'))
- this.deleteFile();
- });
- }
- else
- this._deleteWidget = null;
- }
- this._audio.onloadedmetadata = () => {
- if (this.interfaced())
- this.resetWidget();
- this._showDuration();
- if (this._autoplay)
- this._audio.play();
- };
- this._audio.ontimeupdate = () => {
- if (this._barWidget && !this._seeking)
- this._barWidget.value = (this._audio.currentTime ? Math.floor(this._audio.currentTime / this._audio.duration * 100) : 0);
- this._showCurrentTime();
- };
- this._audio.onplay = () => {
- if (this._playWidget && this._pauseWidget) {
- this._playWidget.hidden = true;
- this._pauseWidget.hidden = false;
- }
- this.notify('audioPlayed', this);
- };
- this._audio.onpause = () => {
- if (this._playWidget && this._pauseWidget) {
- this._pauseWidget.hidden = true;
- this._playWidget.hidden = false;
- }
- this.notify('audioPaused', this);
- };
- this._audio.onended = () => {
- if (this._playWidget && this._pauseWidget) {
- this._pauseWidget.hidden = true;
- this._playWidget.hidden = false;
- }
- this.notify('audioEnded', this);
- };
- this._audio.onerror = () => {
- if (this._playWidget && this._pauseWidget) {
- this._pauseWidget.hidden = true;
- this._playWidget.hidden = false;
- }
- this._audio.removeAttribute('src');
- if (this.interfaced())
- this.resetWidget();
- this._showDuration();
- this.notify('audioError', this);
- };
- return this;
- };
- AudioPlayer.prototype.destroyWidget = function() {
- View.prototype.destroyWidget.call(this);
- this._playWidget = null;
- this._pauseWidget = null;
- this._barWidget = null;
- this._timeWidget = null;
- this._loopWidget = null;
- this._loadWidget = null;
- this._deleteWidget = null;
- this._uploadWidget = null;
- this._statusWidget = null;
- this._recordStartWidget = null;
- this._recordStopWidget = null;
- return this;
- };
- AudioPlayer.prototype.recordStart = function() {
- if (!this._recorder)
- return this;
- if (this._recording || this._uploading)
- return this;
- this._audio.pause();
- this._recording = true;
- this._error = null;
- if (this.interfaced())
- this.resetWidget();
- if (this._mediarecorder === null) {
- const options = {mimeType: this._mediatype, audioBitsPerSecond: 128000};
- navigator.mediaDevices.getUserMedia({audio: true}).then((stream) => {
- this._mediarecorder = new MediaRecorder(stream, options);
- this._mediarecorder.ignoreMutedMedia = true;
- let recordedtime = 0;
- let mediachunks = [];
- this._mediarecorder.ondataavailable = (e) => {
- if (this._timeWidget)
- this._timeWidget.innerText = AudioPlayer._toHHMMSS(++recordedtime);
- mediachunks.push(e.data);
- };
- this._mediarecorder.onstart = () => {
- if (this._recordStartWidget && this._recordStopWidget) {
- this._recordStartWidget.hidden = true;
- this._recordStopWidget.hidden = false;
- }
- if (this._barWidget)
- this._barWidget.value = 0;
- if (this._timeWidget)
- this._timeWidget.innerText = AudioPlayer._toHHMMSS(recordedtime = 0);
- this.notify('audioRecordStarted', this);
- };
- this._mediarecorder.onstop = () => {
- if (this._recordStartWidget && this._recordStopWidget) {
- this._recordStartWidget.hidden = false;
- this._recordStopWidget.hidden = true;
- }
- const blob = new Blob(mediachunks.splice(0, mediachunks.length), {type: this._mediatype});
- if (this._audio.src)
- URL.revokeObjectURL(this._audio.src);
- this._audio.src = URL.createObjectURL(blob);
- this._mediablob = blob;
- this._recording = false;
- this._uploadable = true;
- if (this.interfaced())
- this.resetWidget();
- this.notify('audioRecordStopped', this);
- };
- this._mediarecorder.onerror = () => {
- if (this._recordStartWidget && this._recordStopWidget) {
- this._recordStartWidget.addClass('inerror');
- this._recordStartWidget.hidden = false;
- this._recordStopWidget.hidden = true;
- }
- this._recording = false;
- this._error = 'record';
- if (this.interfaced())
- this.resetWidget();
- this.notify('audioRecordError', this);
- };
- this._mediarecorder.start(1000);
- })
- .catch((err) => {
- this._recorder = false;
- if (this.interfaced())
- this.resetWidget();
- });
- }
- else
- return this;
- };
- AudioPlayer.prototype.recordStop = function() {
- if (this._mediarecorder)
- this._mediarecorder.stop();
- return this;
- };
- AudioPlayer.prototype.uploadFile = function() {
- if (!this._uploadURL)
- return this;
- if (!this._mediablob)
- return this;
- if (this._recording || this._uploading)
- return this;
- const mediablob = this._mediablob;
- const uploadurl = this._uploadURL;
- const chunksize = this._chunksize;
- const filesize = mediablob.size;
- const filetype = mediablob.type;
- const filereader = new FileReader();
- filereader.onloadend = (e) => postdata(e.target.result);
- let offset = 0, progress = 0, blob;
- const uploadslice = () => {
- if (this._statusWidget && filesize > chunksize)
- this._statusWidget.innerText = `${progress}%`;
- blob = mediablob.slice(offset, offset + chunksize);
- filereader.readAsDataURL(blob);
- };
- const postdata = (data) => {
- $.post(uploadurl, {file_size: filesize, file_type: filetype, file_offset: offset, file_data: data})
- .done(() => {
- offset += blob.size;
- progress = Math.floor((offset / filesize) * 100);
- if (progress < 100)
- uploadslice();
- else {
- if (this._statusWidget)
- this._statusWidget.innerText = '';
- this._uploading = false;
- this._uploadable = false;
- this._deletable = true;
- this._error = null;
- if (this.interfaced())
- this.resetWidget();
- this.notify('audioUploaded', this);
- }
- })
- .fail(() => {
- if (this._statusWidget)
- this._statusWidget.innerText = '';
- this._uploading = false;
- this._error = 'upload';
- if (this.interfaced())
- this.resetWidget();
- this.notify('audioError', this);
- });
- };
- this._uploading = true;
- if (this.interfaced())
- this.resetWidget();
- uploadslice();
- return this;
- };
- AudioPlayer.prototype.deleteFile = function() {
- if (!this._deleteURL)
- return this;
- if (this._uploading)
- return this;
- const deleteurl = this._deleteURL;
- const deletefile = () => {
- $.post(deleteurl)
- .done(() => {
- this._uploadable = this._mediablob ? true : false;
- this._deletable = false;
- this._error = null;
- if (this.interfaced())
- this.resetWidget();
- this.notify('audioDeleted', this);
- })
- .fail(() => {
- this._error = 'delete';
- this.resetWidget();
- this.notify('audioError', this);
- });
- };
- deletefile();
- return this;
- AudioPlayer.prototype.loadAudio = function() {
- if (this._recording || this._uploading)
- return this;
- if (this._fileWidget)
- this._fileWidget.click();
- return this;
- };
- AudioPlayer.prototype._loadFile = function(fd) {
- if (!this._audio.canPlayType(fd.type)) {
- this._error = 'load';
- this.resetWidget();
- return;
- }
- this._autoplay = this.playing;
- if (this._audio.src)
- URL.revokeObjectURL(this._audio.src);
- this.src = URL.createObjectURL(fd);
- this._mediablob = fd;
- this._uploadable = true;
- this.resetWidget();
- this.notify('audioLoaded', this);
- AudioPlayer.prototype._showDuration = function() {
- if (this._timeWidget)
- this._timeWidget.innerText = AudioPlayer._toHHMMSS(this._audio.src ? this._audio.duration : 0);
- };
- AudioPlayer.prototype._showCurrentTime = function() {
- if (this._timeWidget)
- this._timeWidget.innerText = AudioPlayer._toHHMMSS(this._audio.src ? this._audio.currentTime : 0);
- };
- AudioPlayer._toHHMMSS = function(nsecs) {
- nsecs = Math.floor(nsecs);
The audio is copied in the disk space of the server in response to a POST by a function which extracts from it the MIME type and the size of the file, the block of data which is transferred, its size and its position in the file. A block of audio data is encoded in BASE64.
Server
In iZend, the file uploadaudio.php is installed directly in the folder actions. To activate the URL /uploadaudio in a website, an entry is added in the file aliases.inc to the list of URLs common to all languages.
- $aliases = array(
- array(
- 'captcha' => 'captcha',
- 'uploadaudio' => 'uploadaudio',
- ),
- 'en' => array(
- ),
- );
Adapt the installation of this function to your development environment.
- define('TMP_DIR', ROOT_DIR . DIRECTORY_SEPARATOR . 'tmp');
- define('AUDIO_MAX_SIZE', 10*1000000);
Defines TMP_DIR
- the folder where the audio file is saved - to the name of the subfolder tmp in the root folder of the site and AUDIO_MAX_SIZE
- the maximum size of an audio - to 10 MB.
- function uploadaudio($lang, $arglist=false) {
Defines the function uploadaudio
which is called by the URL /uploadaudio of the site.
The arguments $lang
and $arglist
are not used.
The content returned by this action is independent of the user's language.
No argument or parameter is expected from the URL.
- $maxfilesize=AUDIO_MAX_SIZE;
- $filetypes=array('audio/mpeg', 'audio/mp3', 'audio/ogg', 'video/ogg');
Initializes $maxfilesize
to AUDIO_MAX_SIZE
and $filetypes
to the list of supported MIME types.
- $type=$data=false;
- $size=$offset=0;
Initializes the variables of the arguments of the POST.
- if (isset($_POST['file_size'])) {
- $size=$_POST['file_size'];
- }
- if (isset($_POST['file_type'])) {
- $type=$_POST['file_type'];
- }
- if (isset($_POST['file_offset'])) {
- $offset=$_POST['file_offset'];
- }
- if (isset($_POST['file_data'])) {
- $data=explode(';base64,', $_POST['file_data']);
- $data=is_array($data) && isset($data[1]) ? base64_decode($data[1]) : false;
- }
Extracts the arguments of the POST. The block of data encoded in BASE64 is decoded.
- if (($offset = filter_var($offset, FILTER_VALIDATE_INT, array('options' => array('min_range' => 0)))) === false)
- goto badrequest;
- if (($size = filter_var($size, FILTER_VALIDATE_INT, array('options' => array('min_range' => 0, 'max_range' => $maxfilesize)))) === false)
- goto badrequest;
- if (!$type or !in_array($type, $filetypes)) {
- goto badrequest;
- }
Checks the arguments of the POST.
- if (!$data) {
- goto badrequest;
- }
- $datasize=strlen($data);
- if ($offset + $datasize > $size) {
- goto badrequest;
- }
Checks the size of the data sent in the POST.
- goto trashfile;
On this server, writing the file is simulated. To check that the audio has been copied properly by listening to it, comment out this instruction and adapt the rest of the code to save the file in a folder which is writable by the server.
- $name='sound';
- switch ($type) {
- case 'audio/mpeg':
- case 'audio/mp3':
- $fname = $name . '.mp3';
- break;
- case 'audio/ogg':
- case 'video/ogg':
- $fname = $name . '.ogg';
- break;
- default:
- goto badrequest;
- }
- $file = TMP_DIR . DIRECTORY_SEPARATOR . $fname;
Defines the name of the audio file. The extension of the file name depends on the MIME type of the audio.
- $fout = @fopen($file, $offset == 0 ? 'wb' : 'cb');
- if ($fout === false) {
- goto internalerror;
- }
Opens the audio file in binary mode. If the POST contains the first block of data, the file is created.
- $r = fseek($fout, $offset);
- if ($r == -1) {
- goto internalerror;
- }
Moves the file pointer to the position of the block of data.
- $r = fwrite($fout, $data);
- if ($r === false) {
- goto internalerror;
- }
Writes the block of data.
- if ($offset + $datasize < $size) {
- return false;
- }
Returns a plain header 200 Ok
if more blocks of data are expected.
- return false;
Returns a plain header 200 Ok
if al the blocks of data have been saved.
NOTE: The code leaves room to process the file like a conversion in different formats with FFmpeg.
- trashfile:
- return false;
Returns a plain header 200 Ok
without saving the data.
- badrequest:
- header('HTTP/1.1 400 Bad Request');
- return false;
Returns a plain header 400 Bad Request
if an element of the POST is invalid.
- internalerror:
- header('HTTP/1.1 500 Internal Error');
- return false;
- }
Returns a plain header 500 Internal Error
if the image couldn't be saved properly.
To ask the server to delete an audio, the player sends a simple POST to the server with no arguments.
- function donothing($lang, $arglist=false) {
- return false;
- }
Defines the function donothing
which is called by the URL /deleteaudio of the site.
donothing
does nothing and always returns a plain header 200 Ok
, i. e. deleting an audio file is simulated.
Test
- <?php $debug=true; ?>
Setting $debug
to true
gives access in the console of the navigator to the variable audioplayer
, the instance of the AudioPlayer.
If $debug
is false
, all the code in JavaScript is protected by a closure function.
- <?php $upload_url='/uploadaudio'; ?>
- <?php $delete_url='/deleteaudio'; ?>
- <?php $chunksize=100000; ?>
Defines the URLs of the functions to save and to delete an audio on the server, the size of the data blocks sent to the server.
- <?php $id=uniqid('id'); ?>
Defines the identifier of the <div>
which surrounds the HTML of the audio player.
- <div id="<?php echo $id; ?>" class="noprint">
- <audio controls preload="metadata">
- <source src="/files/sounds/thanatos.mp3" type="audio/mpeg" />
- <source src="/files/sounds/thanatos.ogg" type="audio/ogg" />
- </audio>
- </div>
Defines a <audio>
element whose parameters <source>
will used to configure the audio player.
This element will be hidden by the code in JavaScript.
- <?php head('javascript', '/objectivejs/Objective.js'); ?>
- <?php head('javascript', '/objectivejs/Responder.js'); ?>
- <?php head('javascript', '/objectivejs/View.js'); ?>
- <?php head('javascript', '/objectivejs/AudioPlayer.js'); ?>
Includes the code of all the necessary classes.
REMINDER: The function head
of the iZend library adds a tag such as <script src="/objectivejs/Objective.js"></script>
to the <head>
section of the document in HTML. Adapt the code to your development environment.
- AudioPlayer.prototype.createWidget = function() {
- const htmlaudiocontrols = [
- '<span class="audiocontrols">',
- '<span class="audioplay"><i class="fas fa-3x fa-play-circle"></i></span>',
- '<span class="audiopause"><i class="fas fa-3x fa-pause-circle"></i></span>',
- '<input class="audiobar" type="range" min="0" max="100" step="1" value="0"/>',
- '<span class="audiotime">00:00:00</span>',
- '<span class="audioloop"><i class="fas fa-sm fa-sync-alt"></i></span>',
- '</span>'
- ].join('\n');
- const htmlmediacontrols = [
- '<span class="mediacontrols">',
- '<span class="recordstart"><i class="fas fa-lg fa-fw fa-microphone"></i></span>',
- '<span class="recordstop"><i class="fas fa-lg fa-fw fa-microphone-alt"></i></span>',
- '<span class="fileload"><i class="fas fa-lg fa-fw fa-file-audio"></i></span>',
- '<span class="audiodelete"><i class="fas fa-lg fa-fw fa-trash"></i></span>',
- '<span class="audioupload"><i class="fas fa-lg fa-fw fa-file-export"></i></span>',
- '<span class="mediastatus"></span>',
- '</span>',
- '<input class="mediafile" type="file" accept="audio/*"/>'
- ].join('\n');
- const html='<div class="ojs_audio">' + '\n' + htmlaudiocontrols + '\n' + htmlmediacontrols + '\n' + '</div>';
- let template = document.createElement('template');
- template.innerHTML = html;
- let widget = template.content.children[0];
- this.setWidget(widget);
- return this;
- }
Defines the method createWidget
of an instance of AudioPlayer.
NOTE: This example uses the icons from Font Awesome.
Adapt it to your development environment.
The HTML of the interface can also be created directly in the document and passed to setWidget
. See AudioPlaylist.
- <?php if (!$debug): ?>
- (function() {
- <?php endif; ?>
Isolates all the code in JavaScript in a closure function if $debug
is false
.
- const options = {
- recorder: true,
- load: true,
- draganddrop: true,
- deleteURL: '<?php echo $delete_url; ?>',
- uploadURL: '<?php echo $upload_url; ?>',
- chunksize: <?php echo $chunksize; ?>
- }
- const audioplayer = new AudioPlayer(options);
Configures and creates an instance of AudioPlayer.
NOTE: Play with the options to see how the interface is configured. Comment out widgets in createWidget
to change the look of the player.
- const container = document.querySelector('#<?php echo $id; ?>');
Retrieves the <div>
which surrounds the HTML of the program.
- const audio = container.querySelector('audio');
- audioplayer.setFromAudio(audio);
Configures the audio source of the player with the original <audio>
element.
- audioplayer.createManagedWidget(container).resetWidget();
Creates and displays the interface of the audio player.
- audio.hidden = true;
Hides the original <audio>
element.
- <?php if (!$debug): ?>
- })();
- <?php endif; ?>
Closes the function which isolates the code in JavaScript if $debug
is false
.
Comments