saut Drupal 10.6.22 -> 11.4.13 (PHP 8.4 local)

- composer update -W: core-recommended ^11.4 (11.4.13), drush ^13.8, gin ^5.0, symfony 7
- scan p2 packages.drupal.org: 98/101 modules ont une release compatible D11; contraintes racine+profil relevées
- takeover custom: audiofield + bulkdelete (plus de branche D11 upstream), q2d_mod blocs convertis en attributs PHP 8
- patch core 2671162 supprimé (fix mergé dans D11), 2645922 gardé, patches image_field_caption réappliqués
- seven retiré (plus dans le core D11), claro déjà présent pour gin
- updb OK, change list entity vide, cim OK, cex commit (normalisation config)
- allow-plugins symfony/runtime ajouté

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
2026-11-22 22:27:41 +01:00
parent 54c5733069
commit 1b0e4b717a
119 changed files with 8771 additions and 1965 deletions
@@ -0,0 +1,11 @@
{
"globals": {
"audiojs": true,
"jPlayerPlaylist": true,
"CirclePlayer": true,
"projekktor": true,
"soundManager": true,
"WaveSurfer": true,
"AudioPlayer": true
}
}
@@ -0,0 +1,59 @@
################
# DrupalCI GitLabCI template
#
# Gitlab-ci.yml to replicate DrupalCI testing for Contrib
#
# With thanks to:
# * The GitLab Acceleration Initiative participants
# * DrupalSpoons
################
################
# Guidelines
#
# This template is designed to give any Contrib maintainer everything they need to test, without requiring modification. It is also designed to keep up to date with Core Development automatically through the use of include files that can be centrally maintained.
#
# However, you can modify this template if you have additional needs for your project.
################
################
# Includes
#
# Additional configuration can be provided through includes.
# One advantage of include files is that if they are updated upstream, the changes affect all pipelines using that include.
#
# Includes can be overridden by re-declaring anything provided in an include, here in gitlab-ci.yml
# https://docs.gitlab.com/ee/ci/yaml/includes.html#override-included-configuration-values
################
include:
################
# DrupalCI includes:
# As long as you include this, any future includes added by the Drupal Association will be accessible to your pipelines automatically.
# View these include files at https://git.drupalcode.org/project/gitlab_templates/
################
- project: $_GITLAB_TEMPLATES_REPO
# "ref" value can be:
# - Recommended (default) - `ref: $_GITLAB_TEMPLATES_REF` - The Drupal Association will update this value to the recommended tag for contrib.
# - Latest - `ref: main` - Get the latest additions and bug fixes as they are merged into the templates.
# - Minor or Major latests - `ref: 1.x-latest` or `ref: 1.0.x-latest` - Get the latest additions within a minor (mostly bugfixes) or major (bugs and new features).
# - Fixed tag - `ref: 1.0.1` - Set the value to a known tag. This will not get any updates.
ref: $_GITLAB_TEMPLATES_REF
file:
- '/includes/include.drupalci.main.yml'
# EXPERIMENTAL: For Drupal 7, remove the above line and uncomment the below.
# - '/includes/include.drupalci.main-d7.yml'
- '/includes/include.drupalci.variables.yml'
- '/includes/include.drupalci.workflows.yml'
################
# Pipeline configuration variables
#
# These are the variables provided to the Run Pipeline form that a user may want to override.
#
# Docs at https://git.drupalcode.org/project/gitlab_templates/-/blob/1.0.x/includes/include.drupalci.variables.yml
################
variables:
# Disables the default phpunit job as we have no tests on this module.
SKIP_PHPUNIT: 1
+339
View File
@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
+151
View File
@@ -0,0 +1,151 @@
Audiofield Module Readme
----------------------
<strong>Project URL</strong> - https://www.drupal.org/project/audiofield
This module creates a new formatter to play either uploaded audio files or
audio links using the File or Link modules.
It introduces a new plugin manager <strong>AudioPlayer</strong>
Installation
------------
To install this module, place it in your modules folder and enable it on the
modules page.
This module will play audio using the HTML5 built-in audio player by default.
Each plugin (other than the default HTML5 audio player) requires installation
of additional files. You can check the current status of installation at
/admin/reports/status or read below for further details on how to install
each player.
To install all external audio player libraries at once, you can run the Drush
command drush audiofield-download (Drush 8) or drush audiofield:download (Drush
9).
Audio.js Audio Player
Audio.js requires installation of the audio.js library located at
http://kolber.github.io/audiojs/ - these files should be downloaded and the
subfolder titled "audiojs" should be placed in /libraries/audiojs such that
the file audio.min.js is found at /libraries/audiojs/.
Install through drush using command drush audiofield-download audiojs
(Drush 8) or drush audiofield:download audiojs (Drush 9).
Audio.js does not offer any theme options, but can be fully styled by custom
CSS.
jPlayer Audio Player
jPlayer requires installation of the jPlayer library located at
http://jplayer.org/ - these files should be downloaded and placed
in /libraries/jplayer. It should be installed such that the file
jquery.jplayer.min.js can be found at /libraries/jplayer/dist/jplayer/.
Install through drush using command drush audiofield-download jplayer
(Drush 8) or drush audiofield:download jplayer (Drush 9).
jPlayer comes bundled with multiple skins by default. You can install
additional skins by placing them in /libraries/jplayer/dist/skin/ and
flushing the drupal cache. The module will automatically detect the
skins and allow for their selection during field configuration.
Alternatively, you can choose "none" for your skin during configuration.
This will provide you baseline audio-player functionality with no
built-in styling so that you can style your player using CSS of your
choosing.
MediaElement Audio Player
MediaElement requires installation of the MediaElement library located at
http://mediaelementjs.com/ - these files should be downloaded and placed
in /libraries/mediaelement such that the file mediaelement-and-player.min.js
is found at /libraries/mediaelement/build/.
Install through drush using command drush audiofield-download mediaelement
(Drush 8) or drush audiofield:download mediaelement (Drush 9).
Projekktor Audio Player
Projekktor requires installation of the Projekktor library located at
https://github.com/frankyghost/projekktor - these files should be downloaded
and placed in /libraries/projekktor. Please note that Projekktor requires
additional installation. This installation is automated with the drush
command, but if you are installing manually, you will also need to compile
Projekktor using the package.json and Gruntfile included in the distribution.
Once you have properly compiled Projekktor, you should find the file
projekktor-1.3.09.min.js at /libraries/projekktor/. This file will not exist
unless the distribution has been properly compiled.
Install through drush using command drush audiofield-download projekktor
(Drush 8) or drush audiofield:download projekktor (Drush 9).
SoundManager Audio Player
WordPress Audio Player requires installation of the SoundManager library
located at http://www.schillmania.com/projects/soundmanager2
These files should be downloaded and placed in /libraries/soundmanager such
that the file soundmanager2-nodebug-jsmin.js can be found at
/libraries/soundmanager/script/.
Install through drush using command drush audiofield-download soundmanager
(Drush 8) or drush audiofield:download soundmanager (Drush 9).
SoundManager is a highly configurable library. However, handling and allowing
for all of the possible configurations and implementations of SoundManager is
outside the scope of this module. As such, we have included several of the
"built-in" themes available in SoundManager's demos. Any further customization
of the player must be done outside of this module.
Wavesurfer Audio Player
Wavesurfer requires installation of the Wavesurfer library located at
https://github.com/katspaugh/wavesurfer.js/releases - these files should be
downloaded and placed in /libraries/wavesurfer such that the file
wavesurfer.min.js is found at /libraries/wavesurfer/dist/.
Please note that there are three versions of Wavesurfer (4.0, 3.0, 2.0, and
< 2.0). Audioplayer supports all installations (installed to the same
directory), but there are small feature differences between these to be
aware of. The drush command will install the latest version.
Install through drush using command drush audiofield-download wavesurfer
(Drush 8) or drush audiofield:download wavesurfer (Drush 9).
Note that you may have to install/build the plugin using after adding the
library if it is not detected ("dist" directory missing). This would occur if
you manually installed the wavesurfer directory. See the wavesurfer
documentation for more info.
Audiowaveform is an additional application which works alongside Wavesurfer
to pre-render waveforms ahead of time and reduce on-load wait times when
displaying Wavesurfer waveforms. To install, see the instructions at
https://github.com/bbc/audiowaveform.
WordPress Audio Player
WordPress Audio Player requires installation of the Standalone version of
the WordPress Audio Player located at http://wpaudioplayer.com/standalone
These files should be downloaded and placed in /libraries/wordpress-audio such
that the file audio-player.js can be found at /libraries/wordpress-audio.
Install through drush using command drush audiofield-download wordpress
(Drush 8) or drush audiofield:download wordpress (Drush 9).
WordPress Audio Player only supports a single skin, but does support a
single audio player for multiple files. However, the multi-file version of
the audio player can make it difficult to notice the existence of additional
tracks, so this module allows the user to opt to use a single player for each
file.
Configuration
-------------
Configuration for the module is performed by modifying field display settings
for File uploads or for Link entities. You begin by selecting Audiofield as the
format for your file or link fields at
/admin/structure/types/manage/CONTENT_TYPE/display . You can then modify the
format settings - select your audio player from the list and you will be
presented with additional configuration options for your selected audio player.
Maintainers
------
Daniel Moberly - <daniel.moberly@gmail.com>
@@ -0,0 +1,12 @@
name: AudioField
description: "Adds audio widget for uploading and playing audio files."
type: module
package: Field types
core_version_requirement: ^9 || ^10 || ^11
# Information added by Drupal.org packaging script on 2026-06-10
project: 'audiofield'
datestamp: 1781072595
version: '8.x-1.14'
@@ -0,0 +1,113 @@
<?php
/**
* @file
* Installation file for Audiofield module.
*/
use Drupal\Core\Link;
use Drupal\Core\Url;
/**
* Implements hook_requirements().
*/
function audiofield_requirements($phase) {
$requirements = [];
if ($phase == 'runtime') {
$requirements['audiofield'] = [
'title' => t('AudioField Players'),
'severity' => REQUIREMENT_INFO,
'value' => '',
'description' => [
'installed' => [
'#theme' => 'item_list',
'#items' => [],
'#title' => '',
'#list_type' => 'ul',
'#attributes' => [],
],
'outdated' => [
'#theme' => 'item_list',
'#items' => [],
'#title' => '',
'#list_type' => 'ul',
'#attributes' => [],
],
'uninstalled' => [
'#theme' => 'item_list',
'#items' => [],
'#title' => '',
'#list_type' => 'ul',
'#attributes' => [],
],
],
];
// Loop over each plugin and make sure it's library is installed.
foreach (\Drupal::service('plugin.manager.audiofield')->getDefinitions() as $pluginName => $plugin) {
// Create an instance of this plugin.
$pluginInstance = \Drupal::service('plugin.manager.audiofield')->createInstance($pluginName);
// Only check install if there is a library for the plugin.
if ($pluginInstance->getPluginLibrary()) {
// Check if the plugin is installed.
if (!$pluginInstance->checkInstalled()) {
// Show a warning here as something is not installed.
$requirements['audiofield']['description']['uninstalled']['#prefix'] = t('Unavailable players');
// Try to print the install directory (will fail if the library itself
// is broken somehow).
try {
$requirements['audiofield']['description']['uninstalled']['#items'][] = t(':library_name library has not been installed. Download from <a href=":url">:url</a> and install in %library', [
':library_name' => $pluginInstance->getPluginTitle(),
':url' => $pluginInstance->getPluginRemoteSource(),
'%library' => $pluginInstance->getPluginLibraryPath(),
]);
}
catch (Exception $e) {
$requirements['audiofield']['description']['uninstalled']['#items'][] = t(':library_name library has not been installed. Download and install in %library', [
':library_name' => $pluginInstance->getPluginTitFle(),
'%library' => $pluginInstance->getPluginLibraryPath(),
]);
}
}
elseif (!$pluginInstance->checkVersion(FALSE)) {
$requirements['audiofield']['description']['outdated']['#prefix'] = t('Out of Date players');
$requirements['audiofield']['description']['outdated']['#items'][] = t(':library_name library (version @version) is installed at %library, but is out of date. Please update to the latest version available at @url, or by running %command', [
':library_name' => $pluginInstance->getPluginTitle(),
'%library' => $pluginInstance->getPluginLibraryPath(),
'@version' => $pluginInstance->getPluginLibraryVersion(),
'@url' => Link::fromTextAndUrl($pluginInstance->getPluginRemoteSource(), Url::fromUri($pluginInstance->getPluginRemoteSource()))->toString(),
'%command' => 'drush audiofield-update',
]);
}
else {
$requirements['audiofield']['description']['installed']['#prefix'] = t('Available players');
$requirements['audiofield']['description']['installed']['#items'][] = t(':library_name library (version @version) has been successfully installed at %library', [
':library_name' => $pluginInstance->getPluginTitle(),
'@version' => $pluginInstance->getPluginLibraryVersion(),
'%library' => $pluginInstance->getPluginLibraryPath(),
]);
}
}
}
// Check if the audiowaveform command is installed for use with wavesurfer.
$requirements['audiowaveform'] = [
'title' => t('Audiowaveform'),
'severity' => REQUIREMENT_INFO,
'value' => '',
'description' => t('Audiowaveform is not currently installed or the PHP function shell_exec is unavailable on this server. Audiowaveform is used to pre-render waveform files for the Audiofield Wavesurfer module. See @audiowaveformlink', [
'@audiowaveformlink' => Link::fromTextAndUrl(t('the Audiowaveform installation instructions'), Url::fromUri('https://github.com/bbc/audiowaveform'))->toString(),
]),
];
if (audiofield_check_audiowaveform_installed()) {
$requirements['audiowaveform']['description'] = t('@version is installed.', [
'@version' => shell_exec('audiowaveform -v'),
]);
$requirements['audiowaveform']['severity'] = REQUIREMENT_OK;
}
}
return $requirements;
}
@@ -0,0 +1,236 @@
audiofield.jplayer:
remote: https://github.com/jplayer/jPlayer/archive/2.9.2.zip
version: &audiofield_jplayer_version "2.9.2"
license: &audiofield_jplayer_license
name: MIT
url: https://github.com/jplayer/jPlayer/blob/2.9.2/MIT-LICENSE.txt
gpl-compatible: true
css:
component:
/libraries/jplayer/lib/circle-player/skin/circle.player.css: {}
css/audiofield.css: {}
js:
/libraries/jplayer/dist/jplayer/jquery.jplayer.min.js: { minified: true }
js/jplayer.builder.js: {}
dependencies:
- core/jquery
- core/once
- core/drupal
- core/drupalSettings
audiofield.jplayer.playlist:
version: *audiofield_jplayer_version
license: *audiofield_jplayer_license
js:
/libraries/jplayer/dist/add-on/jplayer.playlist.min.js: { minified: true }
dependencies:
- audiofield/audiofield.jplayer
audiofield.jplayer.inspector:
version: *audiofield_jplayer_version
license: *audiofield_jplayer_license
js:
/libraries/jplayer/dist/add-on/jquery.jplayer.inspector.min.js: { minified: true }
dependencies:
- audiofield/audiofield.jplayer
audiofield.jplayer.transform2d:
version: *audiofield_jplayer_version
license: *audiofield_jplayer_license
js:
/libraries/jplayer/lib/circle-player/js/jquery.transform2d.js: {}
audiofield.jplayer.grab:
version: *audiofield_jplayer_version
license: *audiofield_jplayer_license
js:
/libraries/jplayer/lib/circle-player/js/jquery.grab.js: {}
audiofield.jplayer.csstransforms:
version: *audiofield_jplayer_version
license: *audiofield_jplayer_license
js:
/libraries/jplayer/lib/circle-player/js/mod.csstransforms.min.js: { minified: true }
audiofield.jplayer.theme_jplayer_circle:
version: *audiofield_jplayer_version
license: *audiofield_jplayer_license
css:
component:
/libraries/jplayer/lib/circle-player/skin/circle.player.css: {}
js:
js/jplayer.circleplayer.fix.js: {}
/libraries/jplayer/lib/circle-player/js/circle.player.js: {}
dependencies:
- audiofield/audiofield.jplayer
- audiofield/audiofield.jplayer.transform2d
- audiofield/audiofield.jplayer.grab
- audiofield/audiofield.jplayer.csstransforms
audiofield.wordpress:
remote: http://wpaudioplayer.com/wp-content/downloads/audio-player-standalone.zip
version: "2.2"
license:
name: MIT
url: http://wpaudioplayer.com/license
gpl-compatible: true
js:
/libraries/wordpress-audio/audio-player.js: {}
js/wordpress.builder.js: {}
dependencies:
- core/jquery
- core/once
- core/drupal
- core/drupalSettings
audiofield.mediaelement:
remote: https://github.com/mediaelement/mediaelement/archive/4.2.5.zip
version: "4.2.5"
license:
name: MIT
url: https://mediaelement.mit-license.org/
gpl-compatible: true
css:
component:
/libraries/mediaelement/build/mediaelementplayer.min.css: { minified: true }
css/audiofield.css: {}
css/audiofield.mediaelement.css: {}
js:
/libraries/mediaelement/build/mediaelement-and-player.min.js: { minified: true }
js/mediaelement.builder.js: {}
dependencies:
- core/jquery
- core/once
- core/drupal
- core/drupalSettings
audiofield.soundmanager:
remote: https://github.com/scottschiller/SoundManager2/archive/V2.97a.20170601.zip
version: &audiofield_soundmanager_version "2.97.20170601"
license: &audiofield_soundmanager_license
name: BSD
url: https://github.com/scottschiller/SoundManager2/blob/V2.97a.20170601/license.txt
gpl-compatible: true
js:
/libraries/soundmanager/script/soundmanager2-nodebug-jsmin.js: { minified: true }
js/soundmanager.builder.js: {}
dependencies:
- core/jquery
- core/once
- core/drupal
- core/drupalSettings
audiofield.soundmanager.default:
version: *audiofield_soundmanager_version
license: *audiofield_soundmanager_license
css:
component:
/libraries/soundmanager/demo/mp3-player-button/css/mp3-player-button.css: {}
js:
/libraries/soundmanager/demo/mp3-player-button/script/mp3-player-button.js: {}
dependencies:
- audiofield/audiofield.soundmanager
audiofield.soundmanager.player360:
version: *audiofield_soundmanager_version
license: *audiofield_soundmanager_license
css:
component:
/libraries/soundmanager/demo/360-player/360player.css: {}
js:
/libraries/soundmanager/demo/360-player/script/berniecode-animator.js: {}
/libraries/soundmanager/demo/360-player/script/360player.js: {}
dependencies:
- audiofield/audiofield.soundmanager
audiofield.soundmanager.barui:
version: *audiofield_soundmanager_version
license: *audiofield_soundmanager_license
css:
component:
/libraries/soundmanager/demo/bar-ui/css/bar-ui.css: {}
js:
/libraries/soundmanager/demo/bar-ui/script/bar-ui.js: {}
dependencies:
- audiofield/audiofield.soundmanager
audiofield.soundmanager.inlineplayer:
version: *audiofield_soundmanager_version
license: *audiofield_soundmanager_license
css:
component:
/libraries/soundmanager/demo/play-mp3-links/css/inlineplayer.css: {}
js:
/libraries/soundmanager/demo/play-mp3-links/script/inlineplayer.js: {}
dependencies:
- audiofield/audiofield.soundmanager
audiofield.soundmanager.pageplayer:
version: *audiofield_soundmanager_version
license: *audiofield_soundmanager_license
css:
component:
/libraries/soundmanager/demo/page-player/css/page-player.css: {}
js:
/libraries/soundmanager/demo/page-player/script/page-player.js: {}
dependencies:
- audiofield/audiofield.soundmanager
audiofield.audiojs:
remote: https://kolber.github.io/audiojs/audiojs.zip
version: "1"
license:
name: MIT
url: https://github.com/kolber/audiojs/blob/1.0.1/LICENSE
gpl-compatible: true
css:
component:
css/audiofield.audiojs.css: {}
js:
/libraries/audiojs/audio.min.js: { minified: true }
js/audiojs.builder.js: {}
dependencies:
- core/jquery
- core/once
- core/drupal
- core/drupalSettings
audiofield.projekktor:
remote: https://github.com/frankyghost/projekktor/archive/1.3.09.zip
version: "1.2.37"
license:
name: GPL
url: https://github.com/frankyghost/projekktor/blob/1.3.09/dist/LICENSE
gpl-compatible: true
css:
component:
/libraries/projekktor/themes/maccaco/projekktor.style.css: {}
css/audiofield.projekktor.css: {}
js:
/libraries/projekktor/dist/projekktor-universal.min.js: { minified: true }
js/projekktor.builder.js: {}
dependencies:
- core/jquery
- core/once
- core/drupal
- core/drupalSettings
audiofield.wavesurfer:
remote: https://github.com/katspaugh/wavesurfer.js/archive/4.0.1.zip
version: "4.0.1"
license:
name: BSD 3-Clause License
url: https://github.com/katspaugh/wavesurfer.js/blob/master/LICENSE
gpl-compatible: true
css:
component:
css/audiofield.wavesurfer.css: {}
js:
/libraries/wavesurfer/dist/wavesurfer.min.js: { minified: true }
js/wavesurfer.builder.js: {}
dependencies:
- core/jquery
- core/once
- core/drupal
- core/drupalSettings
@@ -0,0 +1,168 @@
<?php
/**
* @file
* Drupal Module: Audiofield.
*
* Allows the use of multiple audio player plugins for display of audio files.
*/
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Implements hook_library_info_build().
*/
function audiofield_library_info_build() {
$libraries = [];
// Here we dynamically build a library for each skin.
// This allows users to add custom skins to the library's skins folder.
foreach (_audiofield_list_skins('jplayer_audio_player') as $skin) {
$libraries[$skin['library_name']] = [
'css' => [
'component' => [
$skin['path'] => [
'minified' => TRUE,
],
],
],
'dependencies' => [
'core/jquery',
],
];
}
return $libraries;
}
/**
* Helper function to list available skins.
*/
function _audiofield_list_skins($player) {
$skins = [];
if (file_exists(DRUPAL_ROOT . '/libraries/jplayer') && $player == 'jplayer_audio_player') {
$files = \Drupal::service('file_system')->scanDirectory(DRUPAL_ROOT . '/libraries/jplayer/dist/skin/', '#.*\.min\.css#');
foreach ($files as $file) {
// Generate a human readable name.
$name = preg_replace("/^(jplayer\.)(.*)(\.min)/", '$2', $file->name);
$skins[$name] = [
'library_name' => 'audiofield.jplayer.theme_' . preg_replace('#[^A-Za-z0-9]#', '', $name),
'name' => $name,
'path' => str_replace(DRUPAL_ROOT, '', $file->uri),
];
}
}
ksort($skins);
return $skins;
}
/**
* Implements hook_theme().
*/
function audiofield_theme($existing, $type, $theme, $path) {
return [
'audiofield_download_links' => [
'variables' => [
'links' => NULL,
],
],
'audioplayer' => [
'variables' => [
'plugin_id' => NULL,
'plugin_theme' => NULL,
'files' => NULL,
'settings' => NULL,
],
],
];
}
/**
* Implements hook_theme_suggestions_HOOK_alter().
*/
function audiofield_theme_suggestions_audioplayer_alter(array &$suggestions, array $variables) {
// Suggest a template using the plugin name.
$suggestions[] = 'audioplayer__' . $variables['plugin_id'];
// Suggest a template with the plugin/theme name if it exists.
if (!empty($variables['plugin_theme'])) {
$suggestions[] = 'audioplayer__' . $variables['plugin_id'] . '__' . $variables['plugin_theme'];
}
}
/**
* Implements hook_theme_registry_alter().
*/
function audiofield_theme_registry_alter(&$theme_registry) {
/*
* By default, Drupal 8 does not include theme suggestions from inside the
* module in which they were created, so we must add them manually here.
*/
$path = \Drupal::service('extension.list.module')->getPath('audiofield');
$audioplayer_templates = drupal_find_theme_templates($theme_registry, '.html.twig', $path);
foreach ($audioplayer_templates as &$audioplayer_template) {
$audioplayer_template['type'] = 'module';
$audioplayer_template['preprocess functions'] = ['template_preprocess'];
}
$theme_registry += $audioplayer_templates;
}
/**
* Implements hook_help().
*/
function audiofield_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.audiofield':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('AudioField is a file formatter for the File and Link modules. It allows you to upload or link audio files and play them on your site using one of several audio players available. It supports most audio formats (depends on the selected audio player). Please see <a href=":url">the module documentation</a> for examples of the players in use.', [':url' => 'https://www.drupal.org/docs/8/modules/audiofield']) . '</p>';
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<p>' . t('Audiofield supports the following audio players, which must be downloaded and installed as libraries:') . '</p>';
$output .= '<dl>';
$output .= '<dt>' . t('Default HTML5 audio player') . '</dt>';
$output .= '<dd>' . t('Built into major browsers.') . '</dd>';
$output .= '<dt>' . t('Audio.js') . '</dt>';
$output .= '<dd>' . t('<a href=":url">:url</a>', [
':url' => 'https://kolber.github.io/audiojs/',
]) . '</dd>';
$output .= '<dt>' . t('jPlayer') . '</dt>';
$output .= '<dd>' . t('<a href=":url">:url</a>', [
':url' => 'http://jplayer.org/',
]) . '</dd>';
$output .= '<dt>' . t('MediaElement') . '</dt>';
$output .= '<dd>' . t('<a href=":url">:url</a>', [
':url' => 'http://mediaelementjs.com/',
]) . '</dd>';
$output .= '<dt>' . t('Projekktor') . '</dt>';
$output .= '<dd>' . t('<a href=":url">:url</a>', [
':url' => 'https://github.com/frankyghost/projekktor',
]) . '</dd>';
$output .= '<dt>' . t('SoundManager') . '</dt>';
$output .= '<dd>' . t('<a href=":url">:url</a>', [
':url' => 'http://www.schillmania.com/projects/soundmanager2',
]) . '</dd>';
$output .= '<dt>' . t('wavesurfer.js') . '</dt>';
$output .= '<dd>' . t('<a href=":url">:url</a>', [
':url' => 'https://wavesurfer-js.org',
]) . '</dd>';
$output .= '<dt>' . t('WordPress Audio') . '</dt>';
$output .= '<dd>' . t('<a href=":url">:url</a>', [
':url' => 'http://wpaudioplayer.com',
]) . '</dd>';
$output .= '</dl>';
return $output;
}
}
/**
* Check to see if AudioWaveForm is installed.
*/
function audiofield_check_audiowaveform_installed() {
// Check if shell_exec is callable (required for audiowaveform).
if (is_callable('shell_exec') && stripos(ini_get('disable_functions'), 'shell_exec') === FALSE) {
$shellExecResult = (shell_exec('audiowaveform -v') ?? '');
return (substr($shellExecResult, 0, 13) == 'AudioWaveform');
}
return FALSE;
}
@@ -0,0 +1,4 @@
services:
plugin.manager.audiofield:
class: Drupal\audiofield\AudioFieldPlayerManager
parent: default_plugin_manager
@@ -0,0 +1,79 @@
field.formatter.settings.audiofield_audioplayer:
type: mapping
label: 'Audiofield audio player settings'
mapping:
audio_player:
type: string
label: 'Audio player'
audio_player_jplayer_theme:
type: string
label: 'jplayer theme'
audio_player_wavesurfer_combine_files:
type: boolean
label: 'Combine files into single player'
audio_player_wavesurfer_audiorate:
type: integer
label: 'Audio rate'
audio_player_wavesurfer_autocenter:
type: boolean
label: 'Auto Center'
audio_player_wavesurfer_bargap:
type: integer
label: 'Bar gap'
audio_player_wavesurfer_barheight:
type: integer
label: 'Bar height'
audio_player_wavesurfer_barwidth:
type: integer
label: 'Bar width'
audio_player_wavesurfer_cursorcolor:
type: string
label: 'Cursor color'
audio_player_wavesurfer_cursorwidth:
type: integer
label: 'Cursor width'
audio_player_wavesurfer_forcedecode:
type: boolean
label: 'Force decode'
audio_player_wavesurfer_normalize:
type: boolean
label: 'Normalize'
audio_player_wavesurfer_playnexttrack:
type: boolean
label: 'Autoplay Next Track'
audio_player_wavesurfer_progresscolor:
type: string
label: 'Progress color'
audio_player_wavesurfer_responsive:
type: boolean
label: 'Responsive'
audio_player_wavesurfer_use_peakfile:
type: boolean
label: 'Use peakfile'
audio_player_wavesurfer_wavecolor:
type: string
label: 'Wave color'
audio_player_wordpress_combine_files:
type: boolean
label: 'Combine files into single player'
audio_player_wordpress_animation:
type: boolean
label: 'Animation'
audio_player_soundmanager_theme:
type: string
label: 'Soundmanager theme'
audio_player_initial_volume:
type: integer
label: 'Initial volume'
audio_player_autoplay:
type: boolean
label: 'Autoplay'
audio_player_lazyload:
type: boolean
label: 'Lazy load audio'
download_button:
type: boolean
label: 'Show download button'
download_link:
type: boolean
label: 'Show download link'
@@ -0,0 +1,200 @@
/*
* Audio.js requires custom styling
*/
.audiofield-audiojs audio {
position: absolute;
left: -1px;
}
.audiofield-audiojs {
width: 460px;
height: 36px;
background: #404040;
overflow: hidden;
font-family: monospace;
font-size: 12px;
-webkit-box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.3);
-moz-box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.3);
-o-box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.3);
box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.3);
}
.audiofield-audiojs .play-pauseZ {
width: 40px;
height: 40px;
padding: 4px 6px;
margin: 0px;
float: left;
overflow: hidden;
border-right: 1px solid #000;
}
.audiofield-audiojs p {
display: none;
width: 25px;
height: 40px;
margin: 0px;
cursor: pointer;
}
.audiofield-audiojs .playZ {
display: block;
}
.audiofield-audiojs .scrubberZ {
position: relative;
float: left;
width: 280px;
background: #5a5a5a;
height: 14px;
margin: 10px;
border-left: 0px;
border-bottom: 0px;
overflow: hidden;
}
.audiofield-audiojs .progressZ {
position: absolute;
top: 0px;
left: 0px;
height: 14px;
width: 0px;
background: #ccc;
z-index: 1;
}
.audiofield-audiojs .loadedZ {
position: absolute;
top: 0px;
left: 0px;
height: 14px;
width: 0px;
background: #000;
}
.audiofield-audiojs .timeZ {
float: left;
height: 36px;
line-height: 36px;
margin: 0px 0px 0px 6px;
padding: 0px 6px 0px 12px;
border-left: 1px solid #000;
color: #ddd;
text-shadow: 1px 1px 0px rgba(125, 0, 0, 0.5);
}
.audiofield-audiojs .timeZ em {
padding: 0px 2px 0px 0px;
color: #f9f9f9;
font-style: normal;
}
.audiofield-audiojs .timeZ strong {
padding: 0px 0px 0px 2px;
font-weight: normal;
}
.audiofield-audiojs .error-messageZ {
float: left;
display: none;
margin: 0px 10px;
height: 36px;
width: 400px;
overflow: hidden;
line-height: 36px;
white-space: nowrap;
color: #fff;
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
-icab-text-overflow: ellipsis;
-khtml-text-overflow: ellipsis;
-moz-text-overflow: ellipsis;
-webkit-text-overflow: ellipsis;
}
.audiofield-audiojs .error-messageZ a {
color: #eee;
text-decoration: none;
padding-bottom: 1px;
border-bottom: 1px solid #999;
white-space: normal;
}
.audiofield-audiojs .playZ {
background: url('/libraries/audiojs/player-graphics.gif') -2px -1px no-repeat;
}
.audiofield-audiojs .loadingZ {
background: url('/libraries/audiojs/player-graphics.gif') -2px -31px no-repeat;
}
.audiofield-audiojs .errorZ {
background: url('/libraries/audiojs/player-graphics.gif') -2px -61px no-repeat;
}
.audiofield-audiojs .pauseZ {
background: url('/libraries/audiojs/player-graphics.gif') -2px -91px no-repeat;
}
.audiofield-audiojs.playingZ .playZ,
.audiofield-audiojs.playingZ .loadingZ,
.audiofield-audiojs.playingZ .errorZ {
display: none;
}
.audiofield-audiojs.playingZ .pauseZ {
display: block;
}
.audiofield-audiojs.loadingZ .playZ,
.audiofield-audiojs.loadingZ .pauseZ,
.audiofield-audiojs.loadingZ .errorZ {
display: none;
}
.audiofield-audiojs.loadingZ .loadingZ {
display: block;
}
.audiofield-audiojs.errorZ .timeZ,
.audiofield-audiojs.errorZ .playZ,
.audiofield-audiojs.errorZ .pauseZ,
.audiofield-audiojs.errorZ .scrubberZ,
.audiofield-audiojs.errorZ .loadingZ {
display: none;
}
.audiofield-audiojs.errorZ .errorZ {
display: block;
}
.audiofield-audiojs.errorZ .play-pauseZ p {
cursor: auto;
}
.audiofield-audiojs.errorZ .error-messageZ {
display: block;
}
.audiofield-audiojs-frame ol {
padding: 0px;
margin: 0px;
list-style: decimal-leading-zero inside;
color: #ccc;
width: 460px;
border-top: 1px solid #ccc;
font-size: 0.9em;
}
.audiofield-audiojs-frame ol li {
position: relative;
margin: 0px;
padding: 9px 2px 10px;
border-bottom: 1px solid #ccc;
cursor: pointer;
}
.audiofield-audiojs-frame ol li a {
display: block;
text-indent: -3.3ex;
padding: 0px 0px 0px 20px;
}
.audiofield-audiojs-frame li.playing {
color: #aaa;
text-shadow: 1px 1px 0px rgba(255, 255, 255, 0.3);
}
.audiofield-audiojs-frame li.playing a {
color: #000;
}
.audiofield-audiojs-frame li.playing:before {
content: '♬';
width: 14px;
height: 14px;
padding: 3px;
line-height: 14px;
margin: 0px;
position: absolute;
left: -24px;
top: 9px;
color: #000;
font-size: 13px;
text-shadow: 1px 1px 0px rgba(0, 0, 0, 0.2);
}
@@ -0,0 +1,21 @@
/*
* some players do not expect the box-sizing setting for Drupal 8, so we reset it here
*/
.audiofield {
-webkit-box-sizing: content-box;
box-sizing: content-box;
}
/*
* be certain all floated content is visible
*/
.audiofield:after {
content: "";
clear: both;
display: block;
}
/*
* properly align jPlayer circle player
*/
.cp-circle-frame {
text-align: center;
}
@@ -0,0 +1,6 @@
/*
* Mediaelement requires custom styling to avoid dual-element overlay.
*/
.mediaelementaudio_frame .mejs__mediaelement {
display: none;
}
@@ -0,0 +1,18 @@
/*
* Projekktor requires custom styling to prevent looking like a video player.
*/
.audiofield-projekktor {
height: 38px;
}
.audiofield-projekktor .ppcontrols {
opacity: 100;
}
.audiofield-projekktor .ppdisplay,
.audiofield-projekktor .ppstart {
opacity: 0;
display: none;
}
.audiofield-projekktor.ppstateidle .ppscrubber {
opacity: 0;
display: none;
}
@@ -0,0 +1,40 @@
/*
* Waveform requires custom styling as it is not built in to the library.
*/
.audiofield-wavesurfer .player-button {
color: #fff;
background-color: #337ab7;
display: inline-block;
padding: 6px 12px;
margin-bottom: 0;
text-align: center;
white-space: nowrap;
cursor: pointer;
border: 1px solid transparent;
border-radius: 4px;
width: 55px;
}
.audiofield-wavesurfer .player-button.playpause {
width: 45px;
}
.audiofield-wavesurfer .player-button:hover {
background-color: #286090;
}
.audiofield-wavesurfer .volume {
float: right;
}
.audiofield-wavesurfer.playlist .playlist {
margin-top: 5px;
}
.audiofield-wavesurfer.playlist .playlist .track {
cursor: pointer;
border-bottom: 1px solid black;
padding: 6px 4px;
}
.audiofield-wavesurfer.playlist .playlist .track.playing {
color: #337ab7;
}
.audiofield-wavesurfer.playlist .playlist .track:hover {
background-color: #337ab7;
color: #fff;
}
@@ -0,0 +1,9 @@
services:
audiofield.commands:
class: \Drupal\audiofield\Commands\AudiofieldCommands
arguments:
- '@plugin.manager.audiofield'
- '@file_system'
- '@plugin.manager.archiver'
tags:
- { name: drush.command }
@@ -0,0 +1,81 @@
/**
* @file
* Audiofield build AudioJs audio player.
*/
(($, Drupal, once) => {
'use strict';
Drupal.AudiofieldAudiojs = {};
/**
* Generate an audio.js player.
*
* @param {jQuery} context
* The Drupal context for which we are finding and generating this player.
* @param {jQuery} settings
* The Drupal settings for this player.
*/
Drupal.AudiofieldAudiojs.generate = (context, settings) => {
// Create the media player.
const elements = once('generate-audiojs', `#${settings.element}`, context);
$.each(elements, (index, item) => {
// Initialize the audio player.
const audioPlayer = audiojs.create($(item).find('audio').get(0), {
css: false,
createPlayer: {
markup: false,
playPauseClass: 'play-pauseZ',
scrubberClass: 'scrubberZ',
progressClass: 'progressZ',
loaderClass: 'loadedZ',
timeClass: 'timeZ',
durationClass: 'durationZ',
playedClass: 'playedZ',
errorMessageClass: 'error-messageZ',
playingClass: 'playingZ',
loadingClass: 'loadingZ',
errorClass: 'errorZ',
},
// Handle the end of a track.
trackEnded: () => {
let next = $(context).find(`#${settings.element} ol li.playing`).next();
if (!next.length) {
next = $(context).find(`#${settings.element} ol li:first`);
}
next.addClass('playing').siblings().removeClass('playing');
audioPlayer.load($('a', next).attr('data-src'));
audioPlayer.play();
},
});
// Load in the first track.
$(item).find('ol li:first').addClass('playing');
audioPlayer.load($(item).find('ol a:first').attr('data-src'));
// Load in a track on click.
$(item).find('ol li').click((event) => {
event.preventDefault();
$(event.currentTarget).addClass('playing').siblings().removeClass('playing');
audioPlayer.load($('a', event.currentTarget).attr('data-src'));
audioPlayer.play();
});
});
};
/**
* Attach the behaviors to generate the audio player.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches generation of audio.js audio players.
*/
Drupal.behaviors.audiofieldaudiojs = {
attach: (context, settings) => {
$.each(settings.audiofieldaudiojs, (key, settingEntry) => {
Drupal.AudiofieldAudiojs.generate(context, settingEntry);
});
},
};
})(jQuery, Drupal, once);
@@ -0,0 +1,63 @@
/**
* DO NOT EDIT THIS FILE.
* See the following change record for more information,
* https://www.drupal.org/node/2815083
* @preserve
**/
(function ($, Drupal, once) {
'use strict';
Drupal.AudiofieldAudiojs = {};
Drupal.AudiofieldAudiojs.generate = function (context, settings) {
var elements = once('generate-audiojs', '#' + settings.element, context);
$.each(elements, function (index, item) {
var audioPlayer = audiojs.create($(item).find('audio').get(0), {
css: false,
createPlayer: {
markup: false,
playPauseClass: 'play-pauseZ',
scrubberClass: 'scrubberZ',
progressClass: 'progressZ',
loaderClass: 'loadedZ',
timeClass: 'timeZ',
durationClass: 'durationZ',
playedClass: 'playedZ',
errorMessageClass: 'error-messageZ',
playingClass: 'playingZ',
loadingClass: 'loadingZ',
errorClass: 'errorZ'
},
trackEnded: function trackEnded() {
var next = $(context).find('#' + settings.element + ' ol li.playing').next();
if (!next.length) {
next = $(context).find('#' + settings.element + ' ol li:first');
}
next.addClass('playing').siblings().removeClass('playing');
audioPlayer.load($('a', next).attr('data-src'));
audioPlayer.play();
}
});
$(item).find('ol li:first').addClass('playing');
audioPlayer.load($(item).find('ol a:first').attr('data-src'));
$(item).find('ol li').click(function (event) {
event.preventDefault();
$(event.currentTarget).addClass('playing').siblings().removeClass('playing');
audioPlayer.load($('a', event.currentTarget).attr('data-src'));
audioPlayer.play();
});
});
};
Drupal.behaviors.audiofieldaudiojs = {
attach: function attach(context, settings) {
$.each(settings.audiofieldaudiojs, function (key, settingEntry) {
Drupal.AudiofieldAudiojs.generate(context, settingEntry);
});
}
};
})(jQuery, Drupal, once);
@@ -0,0 +1,172 @@
/**
* @file
* Audiofield build jPlayer audio players of various types.
*/
(($, Drupal, once) => {
'use strict';
Drupal.AudiofieldJplayer = {};
/**
* Generate a jplayer player for the default single file layout.
*
* @param {jQuery} context
* The Drupal context for which we are finding and generating this player.
* @param {jQuery} settings
* The Drupal settings for this player.
*/
Drupal.AudiofieldJplayer.generate = (context, settings) => {
// Create the media player.
const element = once('generate-jplayer', '#jquery_jplayer_' + settings.unique_id, context);
$(element).jPlayer(
{
cssSelectorAncestor: `#jp_container_${settings.unique_id}`,
},
{
ready: () => {
const mediaArray = {
title: settings.description,
};
mediaArray[settings.filetype] = settings.file;
$(`#jquery_jplayer_${settings.unique_id}`, context).jPlayer('setMedia', mediaArray);
},
canplay: () => {
// Handle autoplay.
if (!!settings.autoplay) {
$(`#jquery_jplayer_${settings.unique_id}`, context).jPlayer('play');
}
},
swfPath: '/libraries/jplayer/dist/jplayer',
supplied: settings.filetype,
wmode: 'window',
useStateClassSkin: true,
autoBlur: false,
preload: settings.lazyload,
smoothPlayBar: true,
keyEnabled: true,
remainingDuration: false,
toggleDuration: false,
volume: settings.volume,
},
);
};
/**
* Generate a jplayer formatter for a player.
*
* @param {jQuery} context
* The Drupal context for which we are finding and generating this player.
* @param {jQuery} settings
* The Drupal settings for this player.
*/
Drupal.AudiofieldJplayer.generatePlaylist = (context, settings) => {
var elements = once('generate-jplayer', '#jquery_jplayer_' + settings.unique_id, context);
$.each(elements, (index, item) => {
// Initialize the container audio player.
const thisPlaylist = new jPlayerPlaylist({
jPlayer: $(item),
cssSelectorAncestor: `#jp_container_${settings.unique_id}`,
}, [], {
canplay: () => {
// Handle autoplay.
if (!!settings.autoplay) {
$(item).jPlayer('play');
}
},
playlistOptions: {
enableRemoveControls: false,
},
swfPath: '/libraries/jplayer/dist/jplayer',
wmode: 'window',
useStateClassSkin: true,
autoBlur: false,
preload: settings.lazyload,
smoothPlayBar: true,
keyEnabled: true,
volume: settings.volume,
});
// Loop over each file.
$.each(settings.files, (key, fileEntry) => {
// Build the media array.
const mediaArray = {
title: fileEntry.description,
};
mediaArray[fileEntry.filetype] = fileEntry.file;
// Add the file to the playlist.
thisPlaylist.add(mediaArray);
});
});
};
/**
* Generate a jplayer circle player.
*
* @param {jQuery} context
* The Drupal context for which we are finding and generating this player.
* @param {array} file
* The audio file for which we are generating a player.
*/
Drupal.AudiofieldJplayer.generateCircle = (context, file) => {
// Create the media player.
var elements = once('generate-jplayer', '#jquery_jplayer_' + file.fid, context);
$.each(elements, (index, item) => {
// Build the media array for this player.
const mediaArray = {};
mediaArray[file.filetype] = file.file;
// Initialize the player.
new CirclePlayer(
$(item),
mediaArray,
{
cssSelectorAncestor: `#cp_container_${file.fid}`,
canplay: () => {
// Handle autoplay.
if (!!file.autoplay) {
$(item).jPlayer('play');
}
},
swfPath: '/libraries/jplayer/dist/jplayer',
wmode: 'window',
preload: file.lazyload,
keyEnabled: true,
supplied: file.filetype,
},
);
});
};
/**
* Attach the behaviors to generate the audio player.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches generation of Jplayer audio players.
*/
Drupal.behaviors.audiofieldjplayer = {
attach: (context, settings) => {
$.each(settings.audiofieldjplayer, (key, settingEntry) => {
// Default audio player.
if (settingEntry.playertype === 'default') {
// We can just initialize the audio player direcly.
Drupal.AudiofieldJplayer.generate(context, settingEntry);
}
// Playlist audio player.
else if (settingEntry.playertype === 'playlist') {
Drupal.AudiofieldJplayer.generatePlaylist(context, settingEntry);
}
// Circle audio player.
else if (settingEntry.playertype === 'circle') {
// Loop over the files.
$.each(settingEntry.files, (key2, fileEntry) => {
// Create the player.
Drupal.AudiofieldJplayer.generateCircle(context, fileEntry);
});
}
});
},
};
})(jQuery, Drupal, once);
@@ -0,0 +1,117 @@
/**
* DO NOT EDIT THIS FILE.
* See the following change record for more information,
* https://www.drupal.org/node/2815083
* @preserve
**/
(function ($, Drupal, once) {
'use strict';
Drupal.AudiofieldJplayer = {};
Drupal.AudiofieldJplayer.generate = function (context, settings) {
var element = once('generate-jplayer', '#jquery_jplayer_' + settings.unique_id, context);
$(element).jPlayer({
cssSelectorAncestor: '#jp_container_' + settings.unique_id
}, {
ready: function ready() {
var mediaArray = {
title: settings.description
};
mediaArray[settings.filetype] = settings.file;
$('#jquery_jplayer_' + settings.unique_id, context).jPlayer('setMedia', mediaArray);
},
canplay: function canplay() {
if (!!settings.autoplay) {
$('#jquery_jplayer_' + settings.unique_id, context).jPlayer('play');
}
},
swfPath: '/libraries/jplayer/dist/jplayer',
supplied: settings.filetype,
wmode: 'window',
useStateClassSkin: true,
autoBlur: false,
preload: settings.lazyload,
smoothPlayBar: true,
keyEnabled: true,
remainingDuration: false,
toggleDuration: false,
volume: settings.volume
});
};
Drupal.AudiofieldJplayer.generatePlaylist = function (context, settings) {
var elements = once('generate-jplayer', '#jquery_jplayer_' + settings.unique_id, context);
$.each(elements, function (index, item) {
var thisPlaylist = new jPlayerPlaylist({
jPlayer: $(item),
cssSelectorAncestor: '#jp_container_' + settings.unique_id
}, [], {
canplay: function canplay() {
if (!!settings.autoplay) {
$(item).jPlayer('play');
}
},
playlistOptions: {
enableRemoveControls: false
},
swfPath: '/libraries/jplayer/dist/jplayer',
wmode: 'window',
useStateClassSkin: true,
autoBlur: false,
preload: settings.lazyload,
smoothPlayBar: true,
keyEnabled: true,
volume: settings.volume
});
$.each(settings.files, function (key, fileEntry) {
var mediaArray = {
title: fileEntry.description
};
mediaArray[fileEntry.filetype] = fileEntry.file;
thisPlaylist.add(mediaArray);
});
});
};
Drupal.AudiofieldJplayer.generateCircle = function (context, file) {
var elements = once('generate-jplayer', '#jquery_jplayer_' + file.fid, context);
$.each(elements, function (index, item) {
var mediaArray = {};
mediaArray[file.filetype] = file.file;
new CirclePlayer($(item), mediaArray, {
cssSelectorAncestor: '#cp_container_' + file.fid,
canplay: function canplay() {
if (!!file.autoplay) {
$(item).jPlayer('play');
}
},
swfPath: '/libraries/jplayer/dist/jplayer',
wmode: 'window',
keyEnabled: true,
preload: file.lazyload,
supplied: file.filetype
});
});
};
Drupal.behaviors.audiofieldjplayer = {
attach: function attach(context, settings) {
$.each(settings.audiofieldjplayer, function (key, settingEntry) {
if (settingEntry.playertype === 'default') {
Drupal.AudiofieldJplayer.generate(context, settingEntry);
} else if (settingEntry.playertype === 'playlist') {
Drupal.AudiofieldJplayer.generatePlaylist(context, settingEntry);
} else if (settingEntry.playertype === 'circle') {
$.each(settingEntry.files, function (key2, fileEntry) {
Drupal.AudiofieldJplayer.generateCircle(context, fileEntry);
});
}
});
}
};
})(jQuery, Drupal, once);
@@ -0,0 +1,9 @@
/**
* @file
* Audiofield jPlayer Circleplayer issue fix.
*
* Circleplayer is not properly namespaced, it assumes $ = jQuery.
* We have to define that namespace equivalence here to prevent issues.
*/
var $ = jQuery;
@@ -0,0 +1,8 @@
/**
* DO NOT EDIT THIS FILE.
* See the following change record for more information,
* https://www.drupal.org/node/2815083
* @preserve
**/
var $ = jQuery;
@@ -0,0 +1,51 @@
/**
* @file
* Audiofield build MediaElement audio player.
*/
(($, Drupal, once) => {
'use strict';
Drupal.AudiofieldMediaelement = {};
/**
* Generate a mediaelement player.
*
* @param {jQuery} context
* The Drupal context for which we are finding and generating this player.
* @param {array} file
* The audio file for which we are generating a player.
* @param {jQuery} settings
* The Drupal settings for this player..
*/
Drupal.AudiofieldMediaelement.generate = (context, file, settings) => {
// Create the media player.
const element = once('generate-mediaelement', file, context);
$(element).mediaelementplayer({
startVolume: settings.volume,
loop: false,
enableAutosize: true,
isVideo: false,
});
};
/**
* Attach the behaviors to generate the audio player.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches generation of MediaElement audio players.
*/
Drupal.behaviors.audiofieldmediaelement = {
attach: (context, settings) => {
$.each(settings.audiofieldmediaelement, (key, settingEntry) => {
// Loop over each file.
$.each(settingEntry.elements, (key2, fileEntry) => {
// Create the media player.
Drupal.AudiofieldMediaelement.generate(context, fileEntry, settingEntry);
});
});
},
};
})(jQuery, Drupal, once);
@@ -0,0 +1,32 @@
/**
* DO NOT EDIT THIS FILE.
* See the following change record for more information,
* https://www.drupal.org/node/2815083
* @preserve
**/
(function ($, Drupal, once) {
'use strict';
Drupal.AudiofieldMediaelement = {};
Drupal.AudiofieldMediaelement.generate = function (context, file, settings) {
var element = once('generate-mediaelement', file, context);
$(element).mediaelementplayer({
startVolume: settings.volume,
loop: false,
enableAutosize: true,
isVideo: false
});
};
Drupal.behaviors.audiofieldmediaelement = {
attach: function attach(context, settings) {
$.each(settings.audiofieldmediaelement, function (key, settingEntry) {
$.each(settingEntry.elements, function (key2, fileEntry) {
Drupal.AudiofieldMediaelement.generate(context, fileEntry, settingEntry);
});
});
}
};
})(jQuery, Drupal, once);
@@ -0,0 +1,61 @@
/**
* @file
* Audiofield build Projekktor audio player.
*/
(($, Drupal, once) => {
'use strict';
Drupal.AudiofieldProjekktor = {};
/**
* Generate a projekktor player.
*
* @param {jQuery} context
* The Drupal context for which we are finding and generating this player.
* @param {array} file
* The audio file for which we are generating a player.
* @param {jQuery} settings
* The Drupal settings for this player..
*/
Drupal.AudiofieldProjekktor.generate = (context, file, settings) => {
const elements = once('generate-projekktor', `#${file}`, context);
$.each(elements, (index, item) => {
projekktor($(item), {
debug: false,
playerFlashMP4: settings.swfpath,
playerFlashMP3: settings.swfpath,
enableFullscreen: false,
streamType: 'http',
controls: true,
thereCanBeOnlyOne: true,
volume: settings.volume,
autoplay: !!settings.autoplay,
plugin_display: {},
}, {});
});
};
/**
* Attach the behaviors to generate the audio player.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches generation of Projekktor audio players.
*/
Drupal.behaviors.audiofieldprojekktor = {
attach: (context, settings) => {
// Have to encapsulate because of the way library is created.
jQuery(() => {
$.each(settings.audiofieldprojekktor, (key, settingEntry) => {
// Loop over the attached files.
$.each(settingEntry.files, (key2, file) => {
// Create the audioplayer for each file.
Drupal.AudiofieldProjekktor.generate(context, file, settingEntry);
});
});
});
},
};
})(jQuery, Drupal, once);
@@ -0,0 +1,42 @@
/**
* DO NOT EDIT THIS FILE.
* See the following change record for more information,
* https://www.drupal.org/node/2815083
* @preserve
**/
(function ($, Drupal, once) {
'use strict';
Drupal.AudiofieldProjekktor = {};
Drupal.AudiofieldProjekktor.generate = function (context, file, settings) {
var elements = once('generate-projekktor', '#' + file, context);
$.each(elements, function (index, item) {
projekktor($(item), {
debug: false,
playerFlashMP4: settings.swfpath,
playerFlashMP3: settings.swfpath,
enableFullscreen: false,
streamType: 'http',
controls: true,
thereCanBeOnlyOne: true,
volume: settings.volume,
autoplay: !!settings.autoplay,
plugin_display: {}
}, {});
});
};
Drupal.behaviors.audiofieldprojekktor = {
attach: function attach(context, settings) {
jQuery(function () {
$.each(settings.audiofieldprojekktor, function (key, settingEntry) {
$.each(settingEntry.files, function (key2, file) {
Drupal.AudiofieldProjekktor.generate(context, file, settingEntry);
});
});
});
}
};
})(jQuery, Drupal, once);
@@ -0,0 +1,30 @@
/**
* @file
* Audiofield build SoundManager audio player.
*/
(($, Drupal, once) => {
'use strict';
/**
* Attach the behaviors to generate the audio player.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches generation of Soundmanager audio players.
*/
Drupal.behaviors.audiofieldsoundmanager = {
attach: (context, settings) => {
// Soundmanager intercepts everything so the setup is very simple.
soundManager.setup({
// Required: path to directory containing SM2 SWF files.
url: settings.audiofieldsoundmanager.swfpath,
preferFlash: false,
defaultOptions: {
volume: settings.audiofieldsoundmanager.volume,
},
});
},
};
})(jQuery, Drupal, once);
@@ -0,0 +1,22 @@
/**
* DO NOT EDIT THIS FILE.
* See the following change record for more information,
* https://www.drupal.org/node/2815083
* @preserve
**/
(function ($, Drupal, once) {
'use strict';
Drupal.behaviors.audiofieldsoundmanager = {
attach: function attach(context, settings) {
soundManager.setup({
url: settings.audiofieldsoundmanager.swfpath,
preferFlash: false,
defaultOptions: {
volume: settings.audiofieldsoundmanager.volume
}
});
}
};
})(jQuery, Drupal, once);
@@ -0,0 +1,346 @@
/**
* @file
* Audiofield build Wavesurfer audio player.
*/
(($, Drupal, once) => {
'use strict';
Drupal.AudiofieldWavesurfer = {};
/**
* Generate a wavesurfer player.
*
* @param {jQuery} context
* The Drupal context for which we are finding and generating this player.
* @param {array} file
* The audio file for which we are generating a player.
* @param {jQuery} settings
* The Drupal settings for this player..
*/
Drupal.AudiofieldWavesurfer.generate = (context, file, settings) => {
const elements = once('generate-waveform', `#${file.id}`, context);
$.each(elements, (index, wavecontainer) => {
// Create waveform.
const wavesurfer = WaveSurfer.create({
container: `#${$(wavecontainer).attr('id')} .waveform`,
backend: settings.backend,
audioRate: settings.audioRate,
autoCenter: settings.autoCenter,
barGap: settings.barGap,
barHeight: settings.barHeight,
barWidth: settings.barWidth,
cursorColor: settings.cursorColor,
cursorWidth: settings.cursorWidth,
forceDecode: settings.forceDecode,
normalize: settings.normalize,
progressColor: settings.progressColor,
responsive: settings.responsive,
waveColor: settings.waveColor,
});
// Check if a peak file has been provided.
if (typeof file.peakpath !== 'undefined') {
// Fetch the provided file.
fetch(file.peakpath)
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json();
})
.then(peaks => {
// Normalize the provided peaks data.
Drupal.AudiofieldWavesurfer.normalizePeaks(peaks);
// Load the file.
wavesurfer.load(file.path, peaks.data);
$(wavecontainer).find('.player-button.playpause').html('Play');
})
.catch((e) => {
// Failed to load peaks, just load file normally.
wavesurfer.load(file.path);
console.error('error', e);
});
}
else {
// Load file without peaks.
wavesurfer.load(file.path);
}
// Set the default volume.
wavesurfer.setVolume(settings.volume);
// Handle play/pause.
$(wavecontainer).find('.player-button.playpause').on('click', (event) => {
Drupal.AudiofieldWavesurfer.PlayPause(wavecontainer, wavesurfer);
});
// Handle volume change.
$(wavecontainer).find('.volume').on('change', (event) => {
wavesurfer.setVolume(($(event.currentTarget).val() / 10));
});
// Handle autoplay.
if (!!settings.autoplay) {
wavesurfer.on('ready', wavesurfer.play.bind(wavesurfer));
}
Drupal.AudiofieldWavesurfer.instance = wavesurfer;
});
};
/**
* Normalize a peak file
*
* @param {jQuery} peaks
* The Wavesurfer peaks data for which we are normalizing data.
*/
Drupal.AudiofieldWavesurfer.normalizePeaks = function (peaks) {
var max = peaks.data[0], min = peaks.data[0];
var X, scale;
for (X = 1; X < peaks.data.length; X++) {
if (max < peaks.data[X]) {
max = peaks.data[X];
}
if (min > peaks.data[X]) {
min = peaks.data[X];
}
}
scale = 1.0 / Math.max(Math.abs(min), Math.abs(max));
for (X = 0; X < peaks.data.length; X++) {
peaks.data[X] *= scale;
}
}
/**
* Generate a wavesurfer playlist player.
*
* @param {jQuery} context
* The Drupal context for which we are finding and generating this player.
* @param {jQuery} settings
* The Drupal settings for this player.
*/
Drupal.AudiofieldWavesurfer.generatePlaylist = (context, settings) => {
const elements = once('generate-waveform', `#wavesurfer_playlist-${settings.unique_id}`, context);
$.each(elements, (index, wavecontainer) => {
// Create waveform.
const wavesurfer = WaveSurfer.create({
container: `#${$(wavecontainer).attr('id')} .waveform`,
audioRate: settings.audioRate,
autoCenter: settings.autoCenter,
barGap: settings.barGap,
barHeight: settings.barHeight,
barWidth: settings.barWidth,
cursorColor: settings.cursorColor,
cursorWidth: settings.cursorWidth,
forceDecode: settings.forceDecode,
normalize: settings.normalize,
progressColor: settings.progressColor,
responsive: settings.responsive,
waveColor: settings.waveColor,
});
// Set the default volume.
wavesurfer.setVolume(settings.volume);
// Load the first file.
const first = $(wavecontainer).find('.playlist .track').first();
// Get the label and update it with the first filename.
const label = $(wavecontainer).find('label').first();
label.html(`Playing: ${first.html()}`);
// Set the playing class on the first element.
first.addClass('playing');
// Load the file.
Drupal.AudiofieldWavesurfer.Load(wavecontainer, wavesurfer, first, false);
// Handle play/pause.
$(wavecontainer).find('.player-button.playpause').on('click', (event) => {
Drupal.AudiofieldWavesurfer.PlayPause(wavecontainer, wavesurfer);
});
// Handle next/previous.
$(wavecontainer).find('.player-button.next').on('click', (event) => {
Drupal.AudiofieldWavesurfer.Next(wavecontainer, wavesurfer);
});
$(wavecontainer).find('.player-button.previous').on('click', (event) => {
Drupal.AudiofieldWavesurfer.Previous(wavecontainer, wavesurfer);
});
// Handle clicking track.
$(wavecontainer).find('.playlist .track').on('click', (event) => {
// Check if the track is already playing.
if ($(this).hasClass('playing')) {
// Play/pause the track if it is already loaded.
Drupal.AudiofieldWavesurfer.PlayPause(wavecontainer, wavesurfer);
}
else {
// Load the track.
Drupal.AudiofieldWavesurfer.Load(wavecontainer, wavesurfer, $(event.currentTarget));
}
});
// Handle volume change.
$(wavecontainer).find('.volume').on('change', (event) => {
wavesurfer.setVolume(($(event.currentTarget).val() / 10));
});
// Handle autoplay.
if (!!settings.autoplay) {
wavesurfer.on('ready', wavesurfer.play.bind(wavesurfer));
}
// Handle track finishing.
if (settings.autoplayNextTrack) {
wavesurfer.on('finish', (event) => {
Drupal.AudiofieldWavesurfer.Next(wavecontainer, wavesurfer);
});
}
Drupal.AudiofieldWavesurfer.instance = wavesurfer;
});
};
/**
* Play or pause the wavesurfer and set appropriate classes.
*
* @param {jQuery} wavecontainer
* The container of the wavesurfer element we are accessing.
* @param {jQuery} wavesurfer
* The wavesurfer player we are accessing.
*/
Drupal.AudiofieldWavesurfer.PlayPause = (wavecontainer, wavesurfer) => {
wavesurfer.playPause();
const button = $(wavecontainer).find('.player-button.playpause');
if (wavesurfer.isPlaying()) {
$(wavecontainer).addClass('playing');
button.html('Pause');
}
else {
$(wavecontainer).removeClass('playing');
button.html('Play');
}
};
/**
* Load track on wavesurfer and set appropriate classes.
*
* @param {jQuery} wavecontainer
* The container of the wavesurfer element we are accessing.
* @param {jQuery} wavesurfer
* The wavesurfer player we are accessing.
* @param {jQuery} track
* The track being loaded into the player.
*/
Drupal.AudiofieldWavesurfer.Load = (wavecontainer, wavesurfer, track, playonload = true) => {
// Check for peak file.
const peakpath = track.attr('data-peakpath');
if (peakpath !== '') {
// Fetch the peak file.
fetch(peakpath)
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json();
})
.then(peaks => {
// Normalize the peaks.
Drupal.AudiofieldWavesurfer.normalizePeaks(peaks);
// Load the file with peaks data.
wavesurfer.load(track.attr('data-src'), peaks.data);
})
.catch((e) => {
// Error loading peaks, load file normally.
wavesurfer.load(track.attr('data-src'));
console.error('error', e);
});
}
else {
// Load the track normally.
wavesurfer.load(track.attr('data-src'));
}
wavesurfer.on('ready', (event) => {
if (playonload) {
$(wavecontainer).removeClass('playing');
$(wavecontainer).addClass('playing');
$(wavecontainer).find('.player-button.playpause').html('Pause');
wavesurfer.play();
}
});
// Remove playing from all other tracks.
$(wavecontainer).find('.track').removeClass('playing');
// Set the class on this track.
track.addClass('playing');
// Show what's playing.
$(wavecontainer).find('label').first().html(`Playing: ${track.html()}`);
};
/**
* Skip track forward on wavesurfer and set appropriate classes.
*
* @param {jQuery} wavecontainer
* The container of the wavesurfer element we are accessing.
* @param {jQuery} wavesurfer
* The wavesurfer player we are accessing.
*/
Drupal.AudiofieldWavesurfer.Next = (wavecontainer, wavesurfer) => {
if (wavesurfer.isPlaying()) {
Drupal.AudiofieldWavesurfer.PlayPause(wavecontainer, wavesurfer);
}
// Find the next track.
let track = $(wavecontainer).find('.track.playing').next();
if (typeof track.attr('data-src') === 'undefined') {
track = $(wavecontainer).find('.track').first();
}
// Load the track.
Drupal.AudiofieldWavesurfer.Load(wavecontainer, wavesurfer, track);
};
/**
* Skip track back on wavesurfer and set appropriate classes.
*
* @param {jQuery} wavecontainer
* The container of the wavesurfer element we are accessing.
* @param {jQuery} wavesurfer
* The wavesurfer player we are accessing.
*/
Drupal.AudiofieldWavesurfer.Previous = (wavecontainer, wavesurfer) => {
if (wavesurfer.isPlaying()) {
Drupal.AudiofieldWavesurfer.PlayPause(wavecontainer, wavesurfer);
}
// Find the next track.
let track = $(wavecontainer).find('.track.playing').prev();
if (typeof track.attr('data-src') === 'undefined') {
track = $(wavecontainer).find('.track').last();
}
// Load the track.
Drupal.AudiofieldWavesurfer.Load(wavecontainer, wavesurfer, track);
};
/**
* Attach the behaviors to generate the audio player.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches generation of Wavesurfer audio players.
*/
Drupal.behaviors.audiofieldwavesurfer = {
attach: (context, settings) => {
$.each(settings.audiofieldwavesurfer, (key, settingEntry) => {
// Default audio player.
if (settingEntry.playertype === 'default') {
// Loop over the files.
$.each(settingEntry.files, (key2, file) => {
Drupal.AudiofieldWavesurfer.generate(context, file, settingEntry);
});
}
else if (settingEntry.playertype === 'playlist') {
Drupal.AudiofieldWavesurfer.generatePlaylist(context, settingEntry);
}
});
},
};
})(jQuery, Drupal, once);
@@ -0,0 +1,248 @@
/**
* DO NOT EDIT THIS FILE.
* See the following change record for more information,
* https://www.drupal.org/node/2815083
* @preserve
**/
(function ($, Drupal, once) {
'use strict';
Drupal.AudiofieldWavesurfer = {};
Drupal.AudiofieldWavesurfer.generate = function (context, file, settings) {
var elements = once('generate-waveform', '#' + file.id, context);
$.each(elements, function (index, wavecontainer) {
var wavesurfer = WaveSurfer.create({
container: '#' + $(wavecontainer).attr('id') + ' .waveform',
backend: settings.backend,
audioRate: settings.audioRate,
autoCenter: settings.autoCenter,
barGap: settings.barGap,
barHeight: settings.barHeight,
barWidth: settings.barWidth,
cursorColor: settings.cursorColor,
cursorWidth: settings.cursorWidth,
forceDecode: settings.forceDecode,
normalize: settings.normalize,
progressColor: settings.progressColor,
responsive: settings.responsive,
waveColor: settings.waveColor
});
if (typeof file.peakpath !== 'undefined') {
fetch(file.peakpath)
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json();
})
.then(peaks => {
Drupal.AudiofieldWavesurfer.normalizePeaks(peaks);
wavesurfer.load(file.path, peaks.data);
$(wavecontainer).find('.player-button.playpause').html('Play');
})
.catch((e) => {
wavesurfer.load(file.path);
console.error('error', e);
});
}
else {
wavesurfer.load(file.path);
}
wavesurfer.setVolume(settings.volume);
$(wavecontainer).find('.player-button.playpause').on('click', function (event) {
Drupal.AudiofieldWavesurfer.PlayPause(wavecontainer, wavesurfer);
});
$(wavecontainer).find('.volume').on('change', function (event) {
wavesurfer.setVolume($(event.currentTarget).val() / 10);
});
if (!!settings.autoplay) {
wavesurfer.on('ready', wavesurfer.play.bind(wavesurfer));
}
Drupal.AudiofieldWavesurfer.instance = wavesurfer;
});
};
Drupal.AudiofieldWavesurfer.normalizePeaks = function (peaks) {
var max = peaks.data[0], min = peaks.data[0];
var X, scale;
for (X = 1; X < peaks.data.length; X++) {
if (max < peaks.data[X]) {
max = peaks.data[X];
}
if (min > peaks.data[X]) {
min = peaks.data[X];
}
}
scale = 1.0 / Math.max(Math.abs(min), Math.abs(max));
for (X = 0; X < peaks.data.length; X++) {
peaks.data[X] *= scale;
}
}
Drupal.AudiofieldWavesurfer.generatePlaylist = function (context, settings) {
var elements = once('generate-waveform', '#wavesurfer_playlist-' + settings.unique_id, context);
$.each(elements, function (index, wavecontainer) {
var wavesurfer = WaveSurfer.create({
container: '#' + $(wavecontainer).attr('id') + ' .waveform',
audioRate: settings.audioRate,
autoCenter: settings.autoCenter,
barGap: settings.barGap,
barHeight: settings.barHeight,
barWidth: settings.barWidth,
cursorColor: settings.cursorColor,
cursorWidth: settings.cursorWidth,
forceDecode: settings.forceDecode,
normalize: settings.normalize,
progressColor: settings.progressColor,
responsive: settings.responsive,
waveColor: settings.waveColor
});
wavesurfer.setVolume(settings.volume);
var first = $(wavecontainer).find('.playlist .track').first();
var label = $(wavecontainer).find('label').first();
label.html('Playing: ' + first.html());
Drupal.AudiofieldWavesurfer.Load(wavecontainer, wavesurfer, first, false);
$(wavecontainer).find('.player-button.playpause').on('click', function (event) {
Drupal.AudiofieldWavesurfer.PlayPause(wavecontainer, wavesurfer);
});
$(wavecontainer).find('.player-button.next').on('click', function (event) {
Drupal.AudiofieldWavesurfer.Next(wavecontainer, wavesurfer);
});
$(wavecontainer).find('.player-button.previous').on('click', function (event) {
Drupal.AudiofieldWavesurfer.Previous(wavecontainer, wavesurfer);
});
$(wavecontainer).find('.playlist .track').on('click', function (event) {
if ($(this).hasClass('playing')) {
Drupal.AudiofieldWavesurfer.PlayPause(wavecontainer, wavesurfer);
}
else {
Drupal.AudiofieldWavesurfer.Load(wavecontainer, wavesurfer, $(event.currentTarget));
}
});
$(wavecontainer).find('.volume').on('change', function (event) {
wavesurfer.setVolume($(event.currentTarget).val() / 10);
});
if (!!settings.autoplay) {
wavesurfer.on('ready', wavesurfer.play.bind(wavesurfer));
}
if (settings.autoplayNextTrack) {
wavesurfer.on('finish', function (event) {
Drupal.AudiofieldWavesurfer.Next(wavecontainer, wavesurfer);
});
}
Drupal.AudiofieldWavesurfer.instance = wavesurfer;
});
};
Drupal.AudiofieldWavesurfer.PlayPause = function (wavecontainer, wavesurfer) {
wavesurfer.playPause();
var button = $(wavecontainer).find('.player-button.playpause');
if (wavesurfer.isPlaying()) {
$(wavecontainer).addClass('playing');
button.html('Pause');
} else {
$(wavecontainer).removeClass('playing');
button.html('Play');
}
};
Drupal.AudiofieldWavesurfer.Load = function (wavecontainer, wavesurfer, track, playonload = true) {
var peakpath = track.attr('data-peakpath');
if (peakpath !== '') {
fetch(peakpath)
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json();
})
.then(peaks => {
Drupal.AudiofieldWavesurfer.normalizePeaks(peaks);
wavesurfer.load(track.attr('data-src'), peaks.data);
})
.catch((e) => {
wavesurfer.load(track.attr('data-src'));
console.error('error', e);
});
}
else {
wavesurfer.load(track.attr('data-src'));
}
wavesurfer.on('ready', function (event) {
if (playonload) {
$(wavecontainer).removeClass('playing');
$(wavecontainer).addClass('playing');
$(wavecontainer).find('.player-button.playpause').html('Pause');
wavesurfer.play();
}
});
$(wavecontainer).find('.track').removeClass('playing');
track.addClass('playing');
$(wavecontainer).find('label').first().html('Playing: ' + track.html());
};
Drupal.AudiofieldWavesurfer.Next = function (wavecontainer, wavesurfer) {
if (wavesurfer.isPlaying()) {
Drupal.AudiofieldWavesurfer.PlayPause(wavecontainer, wavesurfer);
}
var track = $(wavecontainer).find('.track.playing').next();
if (typeof track.attr('data-src') === 'undefined') {
track = $(wavecontainer).find('.track').first();
}
Drupal.AudiofieldWavesurfer.Load(wavecontainer, wavesurfer, track);
};
Drupal.AudiofieldWavesurfer.Previous = function (wavecontainer, wavesurfer) {
if (wavesurfer.isPlaying()) {
Drupal.AudiofieldWavesurfer.PlayPause(wavecontainer, wavesurfer);
}
var track = $(wavecontainer).find('.track.playing').prev();
if (typeof track.attr('data-src') === 'undefined') {
track = $(wavecontainer).find('.track').last();
}
Drupal.AudiofieldWavesurfer.Load(wavecontainer, wavesurfer, track);
};
Drupal.behaviors.audiofieldwavesurfer = {
attach: function attach(context, settings) {
$.each(settings.audiofieldwavesurfer, function (key, settingEntry) {
if (settingEntry.playertype === 'default') {
$.each(settingEntry.files, function (key2, file) {
Drupal.AudiofieldWavesurfer.generate(context, file, settingEntry);
});
} else if (settingEntry.playertype === 'playlist') {
Drupal.AudiofieldWavesurfer.generatePlaylist(context, settingEntry);
}
});
}
};
})(jQuery, Drupal, once);
@@ -0,0 +1,65 @@
/**
* @file
* Audiofield build WordPress audio player.
*/
(($, Drupal, once) => {
'use strict';
Drupal.AudiofieldWordpress = {};
/**
* Generate a wordpress player.
*
* @param {jQuery} context
* The Drupal context for which we are finding and generating this player.
* @param {array} file
* The audio file for which we are generating a player.
* @param {jQuery} settings
* The Drupal settings for this player.
*/
Drupal.AudiofieldWordpress.generate = (context, file, settings) => {
let autostartSetting = 'no';
if (!!settings.autoplay) {
autostartSetting = 'yes';
}
const elements = once('generate-waveform', '#wordpressaudioplayer_' + file.unique_id, context);
$.each(elements, (index, item) => {
AudioPlayer.embed($(item).attr('id'), {
soundFile: file.file,
titles: file.title,
autostart: autostartSetting,
loop: 'no',
initialvolume: settings.volume,
checkpolicy: 'yes',
animation: settings.animate,
});
});
};
/**
* Attach the behaviors to generate the audio player.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches generation of Wordpress audio players.
*/
Drupal.behaviors.audiofieldwordpress = {
attach: function buildWordpressPlayers(context, settings) {
$.each(settings.audiofieldwordpress, (key, settingEntry) => {
// Initialize the audioplayer.
AudioPlayer.setup('/libraries/wordpress-audio/player.swf', {
width: 400,
initialvolume: settingEntry.volume,
transparentpagebg: 'yes',
});
// Loop over the files.
$.each(settingEntry.files, (key2, fileEntry) => {
// Generate the player for each file.
Drupal.AudiofieldWordpress.generate(context, fileEntry, settingEntry);
});
});
},
};
})(jQuery, Drupal, once);
@@ -0,0 +1,47 @@
/**
* DO NOT EDIT THIS FILE.
* See the following change record for more information,
* https://www.drupal.org/node/2815083
* @preserve
**/
(function ($, Drupal, once) {
'use strict';
Drupal.AudiofieldWordpress = {};
Drupal.AudiofieldWordpress.generate = function (context, file, settings) {
var autostartSetting = 'no';
if (!!settings.autoplay) {
autostartSetting = 'yes';
}
var elements = once('generate-waveform', '#wordpressaudioplayer_' + file.unique_id, context);
$.each(elements, function (index, item) {
AudioPlayer.embed($(item).attr('id'), {
soundFile: file.file,
titles: file.title,
autostart: autostartSetting,
loop: 'no',
initialvolume: settings.volume,
checkpolicy: 'yes',
animation: settings.animate
});
});
};
Drupal.behaviors.audiofieldwordpress = {
attach: function buildWordpressPlayers(context, settings) {
$.each(settings.audiofieldwordpress, function (key, settingEntry) {
AudioPlayer.setup('/libraries/wordpress-audio/player.swf', {
width: 400,
initialvolume: settingEntry.volume,
transparentpagebg: 'yes'
});
$.each(settingEntry.files, function (key2, fileEntry) {
Drupal.AudiofieldWordpress.generate(context, fileEntry, settingEntry);
});
});
}
};
})(jQuery, Drupal, once);
@@ -0,0 +1,60 @@
<?php
namespace Drupal\audiofield\Annotation;
use Drupal\Component\Annotation\Plugin;
/**
* Defines an AudioPlayer annotation object.
*
* @Annotation
*/
class AudioPlayer extends Plugin {
/**
* The ID for the audio player.
*
* @var string
*/
public $id;
/**
* The audio player's title.
*
* @var \Drupal\Core\Annotation\Translation
*
* @ingroup plugin_translatable
*/
public $title = "";
/**
* The filetypes which function with this audio player.
*
* @var array
*/
public $fileTypes = [];
/**
* The description of this audio player.
*
* @var \Drupal\Core\Annotation\Translation
*
* @ingroup plugin_translatable
*/
public $description = "";
/**
* The main library name for this audio player.
*
* @var string
*/
public $libraryName = "";
/**
* The website of this plugin's audio player library.
*
* @var string
*/
public $website = "";
}
@@ -0,0 +1,32 @@
<?php
namespace Drupal\audiofield;
use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
/**
* Manages audio player plugins.
*/
class AudioFieldPlayerManager extends DefaultPluginManager {
/**
* Constructs a new AudioFieldPlayerManager.
*
* @param \Traversable $namespaces
* An object that implements \Traversable which contains the root paths
* keyed by the corresponding namespace to look for plugin implementations.
* @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
* Cache backend instance to use.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
*/
public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler) {
parent::__construct('Plugin/AudioPlayer', $namespaces, $module_handler, 'Drupal\audiofield\AudioFieldPluginBase', 'Drupal\audiofield\Annotation\AudioPlayer');
$this->alterInfo('audiofield');
$this->setCacheBackend($cache_backend, 'audiofield_audioplayer');
}
}
+644
View File
@@ -0,0 +1,644 @@
<?php
namespace Drupal\audiofield;
use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\file\FileInterface;
use Drupal\Component\Utility\Html;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Component\Utility\Random;
use Drupal\Component\Plugin\PluginBase;
use Drupal\Core\Asset\LibraryDiscoveryInterface;
use Drupal\file\Plugin\Field\FieldType\FileItem;
use Drupal\link\LinkItemInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\File\FileUrlGenerator;
use Drupal\Core\Entity\EntityTypeManagerInterface;
/**
* Base class for audiofield plugins. Includes global functions.
*/
abstract class AudioFieldPluginBase extends PluginBase implements ContainerFactoryPluginInterface {
use StringTranslationTrait;
/**
* Library discovery service.
*
* @var Drupal\Core\Asset\LibraryDiscoveryInterface
*/
protected $libraryDiscovery;
/**
* Messenger service.
*
* @var Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* File System service.
*
* @var Drupal\Core\File\FileSystemInterface
*/
protected $fileSystem;
/**
* Messenger service.
*
* @var Drupal\Core\Logger\LoggerChannelFactoryInterface
*/
protected $loggerFactory;
/**
* File URL generator service.
*
* @var Drupal\Core\File\FileUrlGenerator
*/
protected $fileUrlGenerator;
/**
* The file storage.
*
* @var \Drupal\file\FileStorage
*/
protected $fileStorage;
/**
* {@inheritdoc}
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, LibraryDiscoveryInterface $library_discovery, MessengerInterface $messenger, LoggerChannelFactoryInterface $logger_factory, FileSystemInterface $file_system, FileUrlGenerator $file_url_generator, EntityTypeManagerInterface $entity) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->libraryDiscovery = $library_discovery;
$this->messenger = $messenger;
$this->loggerFactory = $logger_factory;
$this->fileSystem = $file_system;
$this->fileUrlGenerator = $file_url_generator;
$this->fileStorage = $entity->getStorage('file');
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('library.discovery'),
$container->get('messenger'),
$container->get('logger.factory'),
$container->get('file_system'),
$container->get('file_url_generator'),
$container->get('entity_type.manager'),
);
}
/**
* Renders the player.
*
* @param \Drupal\Core\Field\FieldItemListInterface $items
* The uploaded item list.
* @param string $langcode
* The language code.
* @param array $settings
* An array of additional render settings.
*
* @return array
* Returns the rendered array.
*/
abstract public function renderPlayer(FieldItemListInterface $items, $langcode, array $settings);
/**
* Gets the plugin_id of the plugin instance.
*
* @return string
* The plugin_id of the plugin instance.
*/
public function getPluginId() {
return $this->pluginDefinition['id'];
}
/**
* Gets the title of the plugin instance.
*
* @return string
* The title of the plugin instance.
*/
public function getPluginTitle() {
return $this->pluginDefinition['title'];
}
/**
* Gets the name of the main library of the plugin instance.
*
* @return string
* The name of the main library of the plugin instance.
*/
public function getPluginLibraryName() {
return $this->pluginDefinition['libraryName'];
}
/**
* Gets the main library instance of this plugin.
*
* @return array
* The definition of the main library for this plugin.
*/
public function getPluginLibrary() {
// Get the main library for this plugin.
return $this->libraryDiscovery->getLibraryByName('audiofield', 'audiofield.' . $this->getPluginLibraryName());
}
/**
* Parses library to get version number of installed library.
*
* @return string
* The version number of the currently installed library.
*/
public function getPluginLibraryVersion() {
// Default to 1. This is implemented in the plugins.
return '1';
}
/**
* Gets the location of this plugin's library installation.
*
* @return string
* The library path of the plugin instance.
*/
public function getPluginLibraryPath() {
// Get the main library for this plugin.
$library = $this->getPluginLibrary();
return preg_filter('%(^libraries/[^//]+).*%', '/$1', $library['js'][0]['data']);
}
/**
* Gets the remote download source from the plugin's main library.
*
* @return string
* The remote download source of the plugin instance.
*/
public function getPluginRemoteSource() {
// Get the main library for this plugin.
$library = $this->getPluginLibrary();
return $library['remote'];
}
/**
* Gets the definition of the plugin implementation.
*
* @return array
* The plugin definition, as returned by the discovery object used by the
* plugin manager.
*/
public function getPluginDefinition() {
return $this->t('@title: @description. Plugin library can be found at %librarySource.', [
'@title' => $this->getPluginTitle(),
'@description' => $this->pluginDefinition['description'],
'%librarySource' => $this->getPluginRemoteSource(),
]);
}
/**
* Checks to see if this audio plugin has been properly installed.
*
* @param bool $log_error
* Flag to indicate whether or not alert should be logged/shown.
*
* @return bool
* Returns a boolean indicating install state.
*/
public function checkInstalled($log_error = TRUE) {
// Get the main library for this plugin.
$library = $this->getPluginLibrary();
// Check if the library is installed.
if (file_exists(DRUPAL_ROOT . '/' . $library['js'][0]['data'])) {
// Check to make sure the installed version is up to date.
$this->checkVersion($log_error);
return TRUE;
}
return FALSE;
}
/**
* Checks to see if this audio plugin version is up to date.
*
* @param bool $log_error
* Flag to indicate whether or not alert should be logged/shown.
*
* @return bool
* Returns a boolean indicating if version is up to date.
*/
public function checkVersion($log_error = TRUE) {
// Get the main library for this plugin.
$library = $this->getPluginLibrary();
// Check to make sure the installed version is up to date.
if (version_compare($this->getPluginLibraryVersion(), $library['version'], '<')) {
// Log the warning if necessary.
if ($log_error) {
$message_data = [
'@plugin' => $this->getPluginTitle(),
'@version' => $this->getPluginLibraryVersion(),
'@newversion' => $library['version'],
'@download-link' => Link::fromTextAndUrl($this->getPluginRemoteSource(), Url::fromUri($this->getPluginRemoteSource()))->toString(),
'%command' => 'drush audiofield-update',
'@status_report' => Link::createFromRoute('status report', 'system.status')->toString(),
];
$this->loggerFactory->get('audiofield')->warning('Warning: @plugin library is out of date. You should upgrade from version @version to version @newversion. You can manually download the required version here: @download-link or you can install automatically by running the command %command. See the @status_report for more information', $message_data);
$this->messenger->addWarning($this->t('Warning: @plugin library is out of date. You should upgrade from version @version to version @newversion. You can manually download the required version here: @download-link or you can install automatically by running the command %command. See the @status_report for more information', $message_data));
}
return FALSE;
}
return TRUE;
}
/**
* Shows library installation errors for in-use libraries.
*/
public function showInstallError() {
$message_data = [
'@library_name' => $this->getPluginLibraryName(),
'@status_report' => Link::createFromRoute('status report', 'system.status')->toString(),
];
$this->loggerFactory->get('audiofield')->error('Error: @library_name library is not currently installed! See the @status_report for more information.', $message_data);
$this->messenger->addWarning($this->t('Error: @library_name library is not currently installed! See the @status_report for more information.', $message_data));
}
/**
* Validate that a file entity will work with this player.
*
* @param \Drupal\file\FileInterface $file
* A file entity.
*
* @return bool
* Indicates if the file is valid for this player or not.
*/
private function validateFileAgainstPlayer(FileInterface $file) {
// Validate the file extension agains the list of valid extensions.
$errors = file_validate_extensions($file, implode(' ', $this->pluginDefinition["fileTypes"]));
if (count($errors) > 0) {
$message_data = [
'%filename' => $file->getFilename(),
'@player' => $this->getPluginLibraryName(),
'%extensions' => implode(', ', $this->pluginDefinition["fileTypes"]),
];
$this->loggerFactory->get('audiofield')->error('Error playing file %filename: currently selected audio player only supports the following extensions: %extensions', $message_data);
$this->messenger->addWarning($this->t('Error playing file %filename: currently selected audio player only supports the following extensions: %extensions', $message_data));
return FALSE;
}
return TRUE;
}
/**
* Validate that a link entity will work with this player.
*
* @param \Drupal\Core\Url $link
* Url to the link.
*
* @return bool
* Indicates if the link is valid for this player or not.
*/
private function validateLinkAgainstPlayer(Url $link) {
// Check for a valid link and a valid extension.
$extension = pathinfo($link->toString(), PATHINFO_EXTENSION);
if (!UrlHelper::isValid($link->toString(), FALSE) ||empty($extension)) {
// We are currently not validating file types for links.
$message_data = [
'%link' => $link->toString(),
];
$this->loggerFactory->get('audiofield')->error('Error playing file: invalid link: %link', $message_data);
$this->messenger->addWarning($this->t('Error playing file: invalid link: %link', $message_data));
return FALSE;
}
return TRUE;
}
/**
* Get the class type for an entity.
*
* @param \Drupal\file\Plugin\Field\FieldType\FileItem|\Drupal\link\Plugin\Field\FieldType\LinkItem $item
* Item for which we are determining class type.
*
* @return string
* The class type for the item.
*/
protected function getClassType($item) {
// Handle File entity.
if (is_a($item, FileItem::class)) {
return 'FileItem';
}
// Handle Link entity.
elseif ($item instanceof LinkItemInterface) {
return 'LinkItem';
}
return NULL;
}
/**
* Validate that this entity will work with this player.
*
* @param \Drupal\file\Plugin\Field\FieldType\FileItem|\Drupal\link\Plugin\Field\FieldType\LinkItem $item
* Item which we are validating works with the player.
*
* @return bool
* Indicates if the entity is valid for this player or not.
*/
protected function validateEntityAgainstPlayer($item) {
// Handle File entity.
if ($this->getClassType($item) == 'FileItem') {
// Load the associated file.
$file = $this->loadFileFromItem($item);
// Be certain that the file itself actually exists.
if (!$file instanceof FileInterface) {
$this->loggerFactory->get('audiofield')->error('Error: file does not exist.');
$this->messenger->addWarning($this->t('Error: file does not exist.'));
return FALSE;
}
// Validate that this file will work with this player.
return $this->validateFileAgainstPlayer($file);
}
// Handle Link entity.
elseif ($this->getClassType($item) == 'LinkItem') {
// Get the source URL for this item.
$source_url = $this->getAudioSource($item);
// Be certain that the URL itself actually exists.
if (!$source_url instanceof Url) {
$this->loggerFactory->get('audiofield')->error('Error: file does not exist.');
$this->messenger->addWarning($this->t('Error: file does not exist.'));
return FALSE;
}
// Validate that this link will work with this player.
return $this->validateLinkAgainstPlayer($source_url);
}
return FALSE;
}
/**
* Load a file from an audio file entity.
*
* @param \Drupal\file\Plugin\Field\FieldType\FileItem|\Drupal\link\Plugin\Field\FieldType\LinkItem $item
* Item for which we are loading the file entity.
*
* @return \Drupal\file\FileInterface
* FileInterface from the item.
*/
private function loadFileFromItem($item) {
// Load the associated file.
return $this->fileStorage->load($item->get('target_id')->getCastedValue());
}
/**
* Get a unique audofield ID.
*
* @return string
* Unique ID for this audio player.
*/
protected function getUniqueRenderId() {
return Html::getUniqueId('audiofield');
}
/**
* Get a unique ID for an item.
*
* @param \Drupal\file\Plugin\Field\FieldType\FileItem|\Drupal\link\Plugin\Field\FieldType\LinkItem $item
* Item for which we are generating a unique ID.
*
* @return string
* Unique ID for the item.
*/
private function getUniqueId($item) {
// Used to generate unique container.
$random_generator = new Random();
// Handle File entity.
if ($this->getClassType($item) == 'FileItem') {
// Load the associated file.
$file = $this->loadFileFromItem($item);
// Craft a unique ID.
return Html::getUniqueId('file_' . $file->get('fid')->getValue()[0]['value'] . '_' . $random_generator->name(16, TRUE));
}
// Handle Link entity.
elseif ($this->getClassType($item) == 'LinkItem') {
// Craft a unique ID.
return Html::getUniqueId('item_' . $random_generator->name(16, TRUE));
}
return Html::getUniqueId($random_generator->name(16, TRUE));
}
/**
* Get the filetype for an item.
*
* @param \Drupal\file\Plugin\Field\FieldType\FileItem|\Drupal\link\Plugin\Field\FieldType\LinkItem $item
* Item for which we are determining filetype.
*
* @return string
* Filetype for the item.
*/
private function getFiletype($item) {
// Handle File entity.
if ($this->getClassType($item) == 'FileItem') {
// Load the associated file.
$file = $this->loadFileFromItem($item);
return pathinfo($file->getFilename(), PATHINFO_EXTENSION);
}
// Handle Link entity.
elseif ($this->getClassType($item) == 'LinkItem') {
return pathinfo($this->getAudioSource($item)->toString(), PATHINFO_EXTENSION);
}
return '';
}
/**
* Get source URL from an audiofield entity.
*
* @param \Drupal\file\Plugin\Field\FieldType\FileItem|\Drupal\link\Plugin\Field\FieldType\LinkItem $item
* Item for which we are determining source.
*
* @return \Drupal\Core\Url|string
* The source URL of an entity.
*/
private function getAudioSource($item) {
if ($this->getClassType($item) == 'FileItem') {
// Load the associated file.
$file = $this->loadFileFromItem($item);
// Get the file URL.
return $this->fileUrlGenerator->generate($file->getFileUri());
}
// Handle Link entity.
elseif ($this->getClassType($item) == 'LinkItem') {
// Get the file URL.
return $item->getUrl();
}
return '';
}
/**
* Get a title description from an audiofield entity.
*
* @param \Drupal\file\Plugin\Field\FieldType\FileItem|\Drupal\link\Plugin\Field\FieldType\LinkItem $item
* Item for which a title is being generated.
*
* @return string
* The description of an entity.
*/
private function getAudioDescription($item) {
if ($this->getClassType($item) == 'FileItem') {
// Get the file description - use the filename if it doesn't exist.
$entity_description = $item->get('description')->getString();
if (empty($entity_description)) {
// Load the associated file.
$file = $this->loadFileFromItem($item);
return $file->getFilename();
}
return $entity_description;
}
// Handle Link entity.
elseif ($this->getClassType($item) == 'LinkItem') {
// Get the file description - use the filename if it doesn't exist.
$entity_description = $item->get('title')->getString();
if (empty($entity_description)) {
return $item->getUrl()->toString();
}
return $entity_description;
}
return '';
}
/**
* Get required rendering information from an entity.
*
* @param \Drupal\file\Plugin\Field\FieldType\FileItem|\Drupal\link\Plugin\Field\FieldType\LinkItem $item
* Item for which we are getting render information.
*
* @return object
* Render information for an item.
*/
public function getAudioRenderInfo($item) {
return (object) [
'item' => $item,
'description' => $this->getAudioDescription($item),
'url' => $this->getAudioSource($item),
'id' => $this->getUniqueId($item),
'filetype' => $this->getFiletype($item),
];
}
/**
* Used to format file entities for use in the twig themes.
*
* @param object $items
* A list of items for which we need to generate render information.
* @param int $limit
* An upper limit for the number of files to return. 0 indicates unlimited.
*
* @return array
* A render array containing files in the proper format for rendering.
*/
public function getItemRenderList($items, $limit = 0) {
$template_files = [];
foreach ($items as $item) {
// If this entity has passed validation, we render it.
if ($this->validateEntityAgainstPlayer($item)) {
// Get render information for this item.
$renderInfo = $this->getAudioRenderInfo($item);
// Add the file to the render array.
$template_files[] = $renderInfo;
// Return list if we have hit the limit.
if ($limit > 0 && count($template_files) == $limit) {
return $template_files;
}
}
}
return $template_files;
}
/**
* Used to render list of downloads as an item list.
*
* @param object $items
* A list of items for which we need to generate download links..
* @param array $settings
* An array of additional render settings.
*
* @return array
* A render array containing download links.
*/
public function createDownloadList($items, array $settings) {
// Check if download links are turned on and there are items.
if (!$settings['download_link'] || count($items) == 0) {
return [];
}
$links = [];
// Loop over each item.
foreach ($items as $item) {
if ($this->validateEntityAgainstPlayer($item)) {
// Get the source URL for this item.
$source_url = $this->getAudioSource($item);
// Set the download attribute to the filename.
$source_path = $source_url->getUri();
$filename = basename($source_path);
$attributes = $source_url->getOption('attributes');
$attributes['download'] = urldecode($filename);
$source_url->setOption('attributes', $attributes);
// Get the entity description for this item.
$entity_description = $this->getAudioDescription($item);
// Add the link.
$links[] = [
'link' => Link::fromTextAndUrl($entity_description, $source_url)->toString(),
];
}
}
return [
'#theme' => 'audiofield_download_links',
'#links' => $links,
];
}
/**
* Used to render a default player (for fallback).
*
* @param \Drupal\Core\Field\FieldItemListInterface $items
* The uploaded item list.
* @param array $settings
* An array of additional render settings.
*/
public function renderDefaultPlayer(FieldItemListInterface $items, array $settings) {
return [
'audioplayer' => [
'#theme' => 'audioplayer',
'#plugin_id' => 'default',
'#settings' => $settings,
'#files' => $this->getItemRenderList($items),
],
'downloads' => $this->createDownloadList($items, $settings),
];
}
}
@@ -0,0 +1,274 @@
<?php
namespace Drupal\audiofield\Commands;
use Drush\Commands\DrushCommands;
use Drush\Drush;
use Drupal\Core\File\FileSystemInterface;
use Drupal\audiofield\AudioFieldPlayerManager;
use Drupal\Core\Archiver\ArchiverManager;
/**
* A Drush commandfile for Audiofield module.
*/
class AudiofieldCommands extends DrushCommands {
/**
* Library discovery service.
*
* @var Drupal\audiofield\AudioFieldPlayerManager
*/
protected $playerManager;
/**
* File system service.
*
* @var Drupal\Component\FileSystem\FileSystemInterface
*/
protected $fileSystem;
/**
* Archive manager service.
*
* @var Drupal\Core\Archiver\ArchiverManager
*/
protected $archiverManager;
/**
* {@inheritdoc}
*/
public function __construct(AudioFieldPlayerManager $player_manager, FileSystemInterface $file_system, ArchiverManager $archiver_manager) {
parent::__construct();
$this->playerManager = $player_manager;
$this->fileSystem = $file_system;
$this->archiverManager = $archiver_manager;
}
/**
* Downloads the suggested Audiofield libraries from their remote repos.
*
* @param string $installLibrary
* The name of the library. If omitted, all libraries will be installed.
* @param bool $print_messages
* Flag indicating if messages should be displayed.
*
* @command audiofield:download
* @aliases audiofield-download
*/
public function download($installLibrary = '', $print_messages = TRUE) {
// Get a list of the audiofield plugins.
$pluginList = $this->playerManager->getDefinitions();
// If there is an argument, check to make sure its valid.
if (!empty($installLibrary)) {
if (!isset($pluginList[$installLibrary . '_audio_player'])) {
$this->logger()->error(dt('Error: @library is not a valid Audiofield library.', [
'@library' => $installLibrary,
]));
return;
}
// If the argument is valid, we only want to install that plugin.
$pluginList = [$installLibrary . '_audio_player' => $pluginList[$installLibrary . '_audio_player']];
}
// Loop over each plugin and make sure it's library is installed.
foreach ($pluginList as $pluginName => $plugin) {
// Create an instance of this plugin.
$pluginInstance = $this->playerManager->createInstance($pluginName);
// Only check install if there is a library for the plugin.
if (!$pluginInstance->getPluginLibrary()) {
continue;
}
// Skip if the plugin is installed.
if ($pluginInstance->checkInstalled()) {
if ($print_messages) {
$this->logger()->notice(dt('Audiofield library for @library is already installed at @location', [
'@library' => $pluginInstance->getPluginTitle(),
'@location' => $pluginInstance->getPluginLibraryPath(),
]));
}
continue;
}
// Get the library install path.
$path = DRUPAL_ROOT . $pluginInstance->getPluginLibraryPath();
// Create the install directory if it does not exist.
if (!is_dir($path)) {
$this->fileSystem->mkdir($path);
}
// Download the file.
$destination = $this->fileSystem->tempnam($this->fileSystem->getTempDirectory(), 'file.') . "tar.gz";
system_retrieve_file($pluginInstance->getPluginRemoteSource(), $destination, FALSE);
if (!file_exists($destination)) {
// Remove the directory.
$this->fileSystem->rmdir($path);
$this->logger()->error(dt('Error: unable to download @library.', [
'@library' => $pluginInstance->getPluginTitle(),
]));
continue;
}
$this->fileSystem->move($destination, $path . '/audiofield-dl.zip');
if (!file_exists($path . '/audiofield-dl.zip')) {
// Remove the directory where we tried to install.
$this->fileSystem->rmdir($path);
if ($print_messages) {
$this->logger()->error(dt('Error: unable to download Audiofield library @library', [
'@library' => $pluginInstance->getPluginTitle(),
]));
continue;
}
}
// Unzip the file.
$zipFile = $this->archiverManager->getInstance(['filepath' => $path . '/audiofield-dl.zip']);
$zipFile->extract($path);
// Remove the downloaded zip file.
$this->fileSystem->unlink($path . '/audiofield-dl.zip');
// If the library still is not installed, we need to move files.
if (!$pluginInstance->checkInstalled()) {
// Find all folders in this directory and move their
// subdirectories up to the parent directory.
$directories = $this->fileSystem->scanDirectory($path, '/.*?/', [
'recurse' => FALSE,
]);
foreach ($directories as $dirName) {
$this->fileSystem->move($path . '/' . $dirName->filename, $this->fileSystem->getTempDirectory() . '/temp_audiofield', FileSystemInterface::EXISTS_REPLACE);
$this->fileSystem->rmdir($path);
$this->fileSystem->move($this->fileSystem->getTempDirectory() . '/temp_audiofield', $path, FileSystemInterface::EXISTS_REPLACE);
}
// Projekktor source files need to be installed.
if ($pluginInstance->getPluginId() == 'projekktor_audio_player') {
$process = Drush::process('npm install', $path);
$process->run();
$process = Drush::process('grunt --force', $path);
$process->run();
}
// Wavesurfer source files need to be installed.
if ($pluginInstance->getPluginId() == 'wavesurfer_audio_player') {
$this->logger()->notice(dt('Installing @library', [
'@library' => $pluginInstance->getPluginTitle(),
]));
$process = Drush::process('npm install', $path);
$process->run();
$this->logger()->notice(dt('Building @library', [
'@library' => $pluginInstance->getPluginTitle(),
]));
$process = Drush::process('npm run build', $path);
$process->run();
}
}
if ($pluginInstance->checkInstalled()) {
if ($print_messages) {
$this->logger()->notice(dt('Audiofield library for @library has been successfully installed at @location', [
'@library' => $pluginInstance->getPluginTitle(),
'@location' => $pluginInstance->getPluginLibraryPath(),
]));
}
}
else {
// Remove the directory where we tried to install.
$this->fileSystem->rmdir($path);
if ($print_messages) {
$this->logger()->error(dt('Error: unable to install Audiofield library @library', [
'@library' => $pluginInstance->getPluginTitle(),
]));
}
}
}
}
/**
* Updates Audiofield libraries from their remote repos if out of date.
*
* @param string $updateLibrary
* The name of the library. If omitted, all libraries will be updated.
* @param bool $print_messages
* Flag indicating if messages should be displayed.
*
* @command audiofield:update
* @aliases audiofield-update
*/
public function update($updateLibrary = '', $print_messages = TRUE) {
// Get a list of the audiofield plugins.
$pluginList = $this->playerManager->getDefinitions();
// If there is an argument, check to make sure its valid.
if (!empty($updateLibrary)) {
if (!isset($pluginList[$updateLibrary . '_audio_player'])) {
$this->logger()->error(dt('Error: @library is not a valid Audiofield library.', [
'@library' => $updateLibrary,
]));
return;
}
// If the argument is valid, we only want to install that plugin.
$pluginList = [$updateLibrary . '_audio_player' => $pluginList[$updateLibrary . '_audio_player']];
}
// Loop over each plugin and make sure it's library is installed.
foreach ($pluginList as $pluginName => $plugin) {
// Create an instance of this plugin.
$pluginInstance = $this->playerManager->createInstance($pluginName);
// Only check install if there is a library for the plugin.
if (!$pluginInstance->getPluginLibrary()) {
continue;
}
// Get the library install path.
$path = DRUPAL_ROOT . $pluginInstance->getPluginLibraryPath();
// If the library isn't installed at all we just run the install.
if (!$pluginInstance->checkInstalled(FALSE)) {
$this->download($pluginInstance->getPluginLibraryName());
continue;
}
// Don't updating the library if its up to date.
if ($pluginInstance->checkVersion(FALSE)) {
$this->logger()->notice(dt('Audiofield library for @library is already up to date', [
'@library' => $pluginInstance->getPluginTitle(),
]));
continue;
}
// Move the current installation to the temp directory.
$this->fileSystem->move($path, $this->fileSystem->getTempDirectory() . '/temp_audiofield', TRUE);
// If the directory failed to move, just delete it.
if (is_dir($path)) {
$this->fileSystem->rmdir($path);
}
// Run the install command now to get the latest version.
$this->download($updateLibrary, FALSE);
// Check if library has been properly installed.
if ($pluginInstance->checkInstalled()) {
// Remove the temporary directory.
$this->fileSystem->rmdir($this->fileSystem->getTempDirectory() . '/temp_audiofield');
$this->logger()->notice(dt('Audiofield library for @library has been successfully updated at @location', [
'@library' => $pluginInstance->getPluginTitle(),
'@location' => $pluginInstance->getPluginLibraryPath(),
]));
}
else {
// Remove the directory where we tried to install.
$this->fileSystem->rmdir($path);
$this->logger()->error(dt('Error: unable to update Audiofield library @library', [
'@library' => $pluginInstance->getPluginTitle(),
]));
// Restore the original install since we failed to update.
$this->fileSystem->move($this->fileSystem->getTempDirectory() . '/temp_audiofield', $path, TRUE);
}
}
}
}
@@ -0,0 +1,76 @@
<?php
namespace Drupal\audiofield\Plugin\AudioPlayer;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\audiofield\AudioFieldPluginBase;
/**
* Implements the audio.js Audio Player plugin.
*
* @AudioPlayer (
* id = "audiojs_audio_player",
* title = @Translation("audio.js audio player"),
* description = @Translation("Drop-in javascript library using native <audio> tag."),
* fileTypes = {
* "mp3",
* },
* libraryName = "audiojs",
* website = "https://kolber.github.io/audiojs/",
* )
*/
class AudioJsAudioPlayer extends AudioFieldPluginBase {
/**
* {@inheritdoc}
*/
public function renderPlayer(FieldItemListInterface $items, $langcode, array $settings) {
// Check to make sure we're installed.
if (!$this->checkInstalled()) {
// Show the error.
$this->showInstallError();
// Simply return the default rendering so the files are still displayed.
return $this->renderDefaultPlayer($items, $settings);
}
// Start building settings to pass to the javascript audio.js builder.
$player_settings = [
// Audio.js expects this as a 0 - 1 range.
'volume' => ($settings['audio_player_initial_volume'] / 10),
'element' => '',
];
// Create arrays to pass to the twig theme..
$template_settings = $settings;
// Format files for output.
$template_files = $this->getItemRenderList($items);
foreach ($template_files as $renderInfo) {
// Used to generate unique container.
$player_settings['element'] = $template_settings['id'] = 'audiofield_audiojs_' . $renderInfo->id;
}
// If we have at least one audio file, we render.
return [
'audioplayer' => [
'#theme' => 'audioplayer',
'#plugin_id' => 'audiojs',
'#settings' => $template_settings,
'#files' => $template_files,
],
'downloads' => $this->createDownloadList($items, $settings),
'#attached' => [
'library' => [
// Attach the audio.js library.
'audiofield/audiofield.' . $this->getPluginLibraryName(),
],
'drupalSettings' => [
'audiofieldaudiojs' => [
$this->getUniqueRenderId() => $player_settings,
],
],
],
];
}
}
@@ -0,0 +1,39 @@
<?php
namespace Drupal\audiofield\Plugin\AudioPlayer;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\audiofield\AudioFieldPluginBase;
/**
* Implements the Default HTML5 Audio Player plugin.
*
* @AudioPlayer (
* id = "default_mp3_player",
* title = @Translation("default HTML5 audio player"),
* description = @Translation("Default html5 player - built into HTML specification."),
* fileTypes = {
* "mp3", "mp4", "m4a", "3gp", "aac", "wav", "ogg", "oga", "flac", "webm",
* },
* libraryName = "default",
* )
*/
class DefaultMp3Player extends AudioFieldPluginBase {
/**
* {@inheritdoc}
*/
public function renderPlayer(FieldItemListInterface $items, $langcode, array $settings) {
// Simply return the default constructor.
return $this->renderDefaultPlayer($items, $settings);
}
/**
* {@inheritdoc}
*/
public function checkInstalled($log_error = FALSE) {
// This is built in to HTML5, so it is always "installed".
return TRUE;
}
}
@@ -0,0 +1,183 @@
<?php
namespace Drupal\audiofield\Plugin\AudioPlayer;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\audiofield\AudioFieldPluginBase;
use Drupal\Component\Serialization\Json;
/**
* Implements the jPlayer Audio Player plugin.
*
* @AudioPlayer (
* id = "jplayer_audio_player",
* title = @Translation("jPlayer audio player"),
* description = @Translation("Free and open source media library."),
* fileTypes = {
* "mp3", "mp4", "wav", "ogg", "oga", "webm",
* },
* libraryName = "jplayer",
* website = "http://jplayer.org/",
* )
*/
class JPlayerAudioPlayer extends AudioFieldPluginBase {
/**
* {@inheritdoc}
*/
public function renderPlayer(FieldItemListInterface $items, $langcode, array $settings) {
// Check to make sure we're installed.
if (!$this->checkInstalled()) {
// Show the error.
$this->showInstallError();
// Simply return the default rendering so the files are still displayed.
return $this->renderDefaultPlayer($items, $settings);
}
// Create arrays to pass to the twig template.
$template_settings = $settings;
$template_theme = str_replace('audiofield.jplayer.theme_', '', $settings['audio_player_jplayer_theme']);
// JPlayer circle has to render differently - no playlist support, etc.
$player_settings = [];
if ($settings['audio_player_jplayer_theme'] == 'audiofield.jplayer.theme_jplayer_circle') {
// @todo circle player broken for some reason.
// Only require the default library.
$library = 'audiofield/audiofield.' . $this->getPluginLibraryName();
// Start building settings to pass to the javascript jplayer builder.
$player_settings = [
'playertype' => 'circle',
// JPlayer expects this as a 0 - 1 value.
'volume' => ($settings['audio_player_initial_volume'] / 10),
'files' => [],
];
// Format files for output.
$template_files = $this->getItemRenderList($items);
foreach ($template_files as $renderInfo) {
// Add entry to player settings for this file.
$player_settings['files'][] = [
'file' => $renderInfo->url->toString(),
'description' => $renderInfo->description,
'filetype' => $renderInfo->filetype,
'fid' => $renderInfo->id,
'autoplay' => $settings['audio_player_autoplay'],
'lazyload' => $settings['audio_player_lazyload'],
];
}
}
// This is a normal jPlayer skin, so we render normally.
else {
// Need to determine quantity of valid items.
$template_settings['item_count'] = 0;
foreach ($items as $item) {
if ($this->validateEntityAgainstPlayer($item)) {
$template_settings['item_count']++;
}
}
// If there is only a single file, we render as a standard player.
if ($template_settings['item_count'] == 1) {
// Only require the default library.
$library = 'audiofield/audiofield.' . $this->getPluginLibraryName();
// Set the template theme name.
$template_theme = 'default_single';
// Format files for output.
$template_files = $this->getItemRenderList($items, 1);
foreach ($template_files as $renderInfo) {
// Start building settings to pass to the javascript jplayer builder.
$player_settings = [
'playertype' => 'default',
'file' => $renderInfo->url->toString(),
'description' => $renderInfo->description,
'unique_id' => $renderInfo->id,
'filetype' => $renderInfo->filetype,
// JPlayer expects this as a 0 - 1 value.
'volume' => ($settings['audio_player_initial_volume'] / 10),
'autoplay' => $settings['audio_player_autoplay'],
'lazyload' => $settings['audio_player_lazyload'],
];
// Store the unique id for the template.
$template_settings['id'] = $renderInfo->id;
}
}
// If we have multiple files, we need to render this as a playlist.
else {
// Requires the playlist library.
$library = 'audiofield/audiofield.' . $this->getPluginLibraryName() . '.playlist';
// Set the template theme name.
$template_theme = 'default_multiple';
// Start building settings to pass to the javascript jplayer builder.
$player_settings = [
'playertype' => 'playlist',
// JPlayer expects this as a 0 - 1 value.
'volume' => ($settings['audio_player_initial_volume'] / 10),
'files' => [],
'filetypes' => [],
'autoplay' => $settings['audio_player_autoplay'],
'lazyload' => $settings['audio_player_lazyload'],
];
// Format files for output.
$template_files = $this->getItemRenderList($items);
foreach ($template_files as $renderInfo) {
// Add entry to player settings for this file.
$player_settings['files'][] = [
'file' => $renderInfo->url->toString(),
'description' => $renderInfo->description,
'filetype' => $renderInfo->filetype,
];
$player_settings['filetypes'][] = $renderInfo->filetype;
// Used to generate unique container.
$player_settings['unique_id'] = $template_settings['id'] = $renderInfo->id;
}
// Use only unique values in the filetypes.
$player_settings['filetypes'] = array_unique($player_settings['filetypes']);
}
}
return [
'audioplayer' => [
'#theme' => 'audioplayer',
'#plugin_id' => 'jplayer',
'#plugin_theme' => $template_theme,
'#settings' => $template_settings,
'#files' => $template_files,
],
'downloads' => $this->createDownloadList($items, $settings),
'#attached' => [
'library' => [
// Attach the jPlayer library.
$library,
// Attach the jPlayer theme.
'audiofield/' . $settings['audio_player_jplayer_theme'],
],
'drupalSettings' => [
'audiofieldjplayer' => [
$this->getUniqueRenderId() => $player_settings,
],
],
],
];
}
/**
* {@inheritdoc}
*/
public function getPluginLibraryVersion() {
// Parse the JSON file for version info.
$library_path = $this->fileSystem->realpath(DRUPAL_ROOT . $this->getPluginLibraryPath() . '/package.json');
$library_data = Json::decode(file_get_contents($library_path));
return $library_data['version'];
}
}
@@ -0,0 +1,84 @@
<?php
namespace Drupal\audiofield\Plugin\AudioPlayer;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\audiofield\AudioFieldPluginBase;
use Drupal\Component\Serialization\Json;
/**
* Implements the MediaElement Audio Player plugin.
*
* @AudioPlayer (
* id = "mediaelement_audio_player",
* title = @Translation("MediaElement audio player"),
* description = @Translation("A dependable HTML media framework."),
* fileTypes = {
* "mp3", "oga", "ogg", "wav",
* },
* libraryName = "mediaelement",
* website = "http://mediaelementjs.com/",
* )
*/
class MediaElementAudioPlayer extends AudioFieldPluginBase {
/**
* {@inheritdoc}
*/
public function renderPlayer(FieldItemListInterface $items, $langcode, array $settings) {
// Check to make sure we're installed.
if (!$this->checkInstalled()) {
// Show the error.
$this->showInstallError();
// Simply return the default rendering so the files are still displayed.
return $this->renderDefaultPlayer($items, $settings);
}
// Start building settings to pass to the javascript MediaElement builder.
$player_settings = [
// MediaElement expects this as a 0 - 1 range.
'volume' => ($settings['audio_player_initial_volume'] / 10),
'elements' => [],
];
// Format files for output.
$template_files = $this->getItemRenderList($items);
foreach ($template_files as $renderInfo) {
// Pass the element name for the player so we know what to render.
$player_settings['elements'][] = '#mediaelement_player_' . $renderInfo->id;
}
return [
'audioplayer' => [
'#theme' => 'audioplayer',
'#plugin_id' => 'mediaelement',
'#settings' => $settings,
'#files' => $template_files,
],
'downloads' => $this->createDownloadList($items, $settings),
'#attached' => [
'library' => [
// Attach the MediaElement library.
'audiofield/audiofield.' . $this->getPluginLibraryName(),
],
'drupalSettings' => [
'audiofieldmediaelement' => [
$this->getUniqueRenderId() => $player_settings,
],
],
],
];
}
/**
* {@inheritdoc}
*/
public function getPluginLibraryVersion() {
// Parse the JSON file for version info.
$library_path = $this->fileSystem->realpath(DRUPAL_ROOT . $this->getPluginLibraryPath() . '/package.json');
$library_data = Json::decode(file_get_contents($library_path));
return $library_data['version'];
}
}
@@ -0,0 +1,86 @@
<?php
namespace Drupal\audiofield\Plugin\AudioPlayer;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\audiofield\AudioFieldPluginBase;
use Drupal\Component\Serialization\Json;
/**
* Implements the Projekktor Audio Player plugin.
*
* @AudioPlayer (
* id = "projekktor_audio_player",
* title = @Translation("Projekktor audio player"),
* description = @Translation("Free Web Video Player (converted for audio)"),
* fileTypes = {
* "mp3", "mp4", "ogg", "oga", "wav",
* },
* libraryName = "projekktor",
* website = "http://www.projekktor.com/",
* )
*/
class ProjekktorAudioPlayer extends AudioFieldPluginBase {
/**
* {@inheritdoc}
*/
public function renderPlayer(FieldItemListInterface $items, $langcode, array $settings) {
// Check to make sure we're installed.
if (!$this->checkInstalled()) {
// Show the error.
$this->showInstallError();
// Simply return the default rendering so the files are still displayed.
return $this->renderDefaultPlayer($items, $settings);
}
// Start building settings to pass to the javascript projekktor builder.
$player_settings = [
// Projekktor expects this as a 0 - 1 range.
'volume' => ($settings['audio_player_initial_volume'] / 10),
'swfpath' => $this->getPluginLibraryPath() . '/swf/Jarisplayer/jarisplayer.swf',
'files' => [],
'autoplay' => $settings['audio_player_autoplay'],
];
// Format files for output.
$template_files = $this->getItemRenderList($items);
foreach ($template_files as $renderInfo) {
// Add this file to the render settings.
$player_settings['files'][] = $renderInfo->id;
}
return [
'audioplayer' => [
'#theme' => 'audioplayer',
'#plugin_id' => 'projekktor',
'#settings' => $settings,
'#files' => $template_files,
],
'downloads' => $this->createDownloadList($items, $settings),
'#attached' => [
'library' => [
// Attach the projekktor library.
'audiofield/audiofield.' . $this->getPluginLibraryName(),
],
'drupalSettings' => [
'audiofieldprojekktor' => [
$this->getUniqueRenderId() => $player_settings,
],
],
],
];
}
/**
* {@inheritdoc}
*/
public function getPluginLibraryVersion() {
// Parse the JSON file for version info.
$library_path = $this->fileSystem->realpath(DRUPAL_ROOT . $this->getPluginLibraryPath() . '/package.json');
$library_data = Json::decode(file_get_contents($library_path));
return $library_data['version'];
}
}
@@ -0,0 +1,84 @@
<?php
namespace Drupal\audiofield\Plugin\AudioPlayer;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\audiofield\AudioFieldPluginBase;
use Drupal\Component\Serialization\Json;
/**
* Implements the SoundManager Audio Player plugin.
*
* @AudioPlayer (
* id = "soundmanager_audio_player",
* title = @Translation("SoundManager audio player"),
* description = @Translation("Simple, reliable cross-platform audio."),
* fileTypes = {
* "mp3", "mp4", "ogg", "oga", "wav", "flac",
* },
* libraryName = "soundmanager",
* website = "http://www.schillmania.com/projects/soundmanager2",
* )
*/
class SoundManagerAudioPlayer extends AudioFieldPluginBase {
/**
* {@inheritdoc}
*/
public function renderPlayer(FieldItemListInterface $items, $langcode, array $settings) {
// Check to make sure we're installed.
if (!$this->checkInstalled()) {
// Show the error.
$this->showInstallError();
// Simply return the default rendering so the files are still displayed.
return $this->renderDefaultPlayer($items, $settings);
}
// Create arrays to pass to the twig template.
$template_settings = $settings;
$template_settings['count'] = count($items);
// Start building settings to pass to the javascript SoundManager builder.
$player_settings = [
// SoundManager expects this as a 0 - 100 range.
'volume' => ($settings['audio_player_initial_volume'] * 10),
'swfpath' => $this->getPluginLibraryPath() . '/swf/',
];
return [
'audioplayer' => [
'#theme' => 'audioplayer',
'#plugin_id' => 'soundmanager',
'#plugin_theme' => $settings['audio_player_soundmanager_theme'],
'#settings' => $template_settings,
'#files' => $this->getItemRenderList($items),
],
'downloads' => $this->createDownloadList($items, $settings),
'#attached' => [
'library' => [
// Attach the SoundManager library.
'audiofield/audiofield.' . $this->getPluginLibraryName(),
// Attach the skin library.
'audiofield/audiofield.' . $this->getPluginLibraryName() . '.' . $settings['audio_player_soundmanager_theme'],
],
'drupalSettings' => [
'audiofieldsoundmanager' => [
$this->getUniqueRenderId() => $player_settings,
],
],
],
];
}
/**
* {@inheritdoc}
*/
public function getPluginLibraryVersion() {
// Parse the JSON file for version info.
$library_path = $this->fileSystem->realpath(DRUPAL_ROOT . $this->getPluginLibraryPath() . '/package.json');
$library_data = Json::decode(file_get_contents($library_path));
return $library_data['version'];
}
}
@@ -0,0 +1,203 @@
<?php
namespace Drupal\audiofield\Plugin\AudioPlayer;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\audiofield\AudioFieldPluginBase;
use Drupal\Component\Serialization\Json;
use Drupal\file\Entity\File;
use Drupal\Core\Link;
use Drupal\Core\Asset\LibraryDiscoveryInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\File\FileUrlGenerator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
/**
* Implements the Wavesurfer Audio Player plugin.
*
* @AudioPlayer (
* id = "wavesurfer_audio_player",
* title = @Translation("Wavesurfer audio player"),
* description = @Translation("A customizable audio waveform visualization, built on top of Web Audio API and HTML5 Canvas."),
* fileTypes = {
* "mp3", "ogg", "oga", "wav",
* },
* libraryName = "wavesurfer",
* website = "https://github.com/katspaugh/wavesurfer.js",
* )
*/
class WavesurferAudioPlayer extends AudioFieldPluginBase {
/**
* Module handler service.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* {@inheritdoc}
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, LibraryDiscoveryInterface $library_discovery, MessengerInterface $messenger, LoggerChannelFactoryInterface $logger_factory, FileSystemInterface $file_system, ModuleHandlerInterface $module_handler, FileUrlGenerator $file_url_generator, EntityTypeManagerInterface $entity) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $library_discovery, $messenger, $logger_factory, $file_system, $file_url_generator, $entity);
$this->moduleHandler = $module_handler;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('library.discovery'),
$container->get('messenger'),
$container->get('logger.factory'),
$container->get('file_system'),
$container->get('module_handler'),
$container->get('file_url_generator'),
$container->get('entity_type.manager'),
);
}
/**
* {@inheritdoc}
*/
public function renderPlayer(FieldItemListInterface $items, $langcode, array $settings) {
// Check to make sure we're installed.
if (!$this->checkInstalled()) {
// Show the error.
$this->showInstallError();
// Simply return the default rendering so the files are still displayed.
return $this->renderDefaultPlayer($items, $settings);
}
// Create arrays to pass to the twig template.
$template_files = [];
// Get a unique render Id.
$settings['unique_id'] = $this->getUniqueRenderId();
// Start building settings to pass to the javascript wavesurfer builder.
$player_settings = [
// Wavesurfer expects this as a 0 - 1 range.
'volume' => ($settings['audio_player_initial_volume'] / 10),
'playertype' => ($settings['audio_player_wavesurfer_combine_files'] ? 'playlist' : 'default'),
'files' => [],
'audioRate' => $settings['audio_player_wavesurfer_audiorate'],
'autoCenter' => $settings['audio_player_wavesurfer_autocenter'],
'backend' => $settings['audio_player_wavesurfer_backend'],
'barGap' => $settings['audio_player_wavesurfer_bargap'],
'barHeight' => $settings['audio_player_wavesurfer_barheight'],
'barWidth' => $settings['audio_player_wavesurfer_barwidth'],
'cursorColor' => $settings['audio_player_wavesurfer_cursorcolor'],
'cursorWidth' => $settings['audio_player_wavesurfer_cursorwidth'],
'forceDecode' => $settings['audio_player_wavesurfer_forcedecode'],
'normalize' => $settings['audio_player_wavesurfer_normalize'],
'progressColor' => $settings['audio_player_wavesurfer_progresscolor'],
'responsive' => $settings['audio_player_wavesurfer_responsive'],
'waveColor' => $settings['audio_player_wavesurfer_wavecolor'],
'autoplayNextTrack' => $settings['audio_player_wavesurfer_playnexttrack'],
'autoplay' => $settings['audio_player_autoplay'],
'unique_id' => $settings['unique_id'],
];
// Format files for output.
$template_files = $this->getItemRenderList($items);
foreach ($template_files as &$renderInfo) {
// Generate settings for this file.
$fileSettings = [
'id' => $renderInfo->id,
'path' => $renderInfo->url->toString(),
];
// Check for Peak files.
if ($settings['audio_player_wavesurfer_use_peakfile'] && $this->getClassType($renderInfo->item) == 'FileItem') {
// Load the associated file.
$file = File::load($renderInfo->item->get('target_id')->getCastedValue());
// Get the file URL.
$deliveryUrl = $file->getFileUri();
// Get the file information so we can determin extension.
$deliveryFileInfo = pathinfo($this->fileUrlGenerator->generateAbsoluteString($deliveryUrl));
// Generate the URL for finding the peak file.
$peakData = [
'url' => dirname($deliveryUrl) . '/' . $deliveryFileInfo['filename'] . '.json',
'arguments' => '--pixels-per-second 20 --bits 8',
];
// Allow other modules to alter path data.
$this->moduleHandler->alter('audiofield_wavesurfer_peak', $peakData);
// Get the real path.
$peakPath = $this->fileSystem->realpath($peakData['url']);
// If the file is missing and Audiowaveform is installed.
if (!file_exists($peakPath) && audiofield_check_audiowaveform_installed()) {
$deliveryPath = escapeshellarg($this->fileSystem->realpath($deliveryUrl));
$peakPath = escapeshellarg($peakPath);
$peakArguments = $peakData['arguments'];
// Generate the data file.
shell_exec("audiowaveform -i $deliveryPath -o $peakPath $peakArguments");
// If the file didn't generate, log/report the error.
if (!file_exists($peakData['url'])) {
$message_data = [
'@status_report' => Link::createFromRoute('status report', 'system.status')->toString(),
];
$this->loggerFactory->get('audiofield')->warning('Warning: Unable to generate Waveform peak file. Please check your installation of audiowaveform. More information available in the @status_report.', $message_data);
$this->messenger->addWarning($this->t('Warning: Unable to generate Waveform peak file. Please check your installation of audiowaveform. More information available in the @status_report.', $message_data));
}
}
// If the file exists, add it to the jQuery and template settings.
if (file_exists($peakData['url'])) {
$renderInfo->peakpath = $fileSettings['peakpath'] = $this->fileUrlGenerator->generateAbsoluteString($peakData['url']);
}
}
// Add this file to the render settings.
$player_settings['files'][] = $fileSettings;
}
return [
'audioplayer' => [
'#theme' => 'audioplayer',
'#plugin_id' => 'wavesurfer',
'#plugin_theme' => $player_settings['playertype'],
'#settings' => $settings,
'#files' => $template_files,
],
'downloads' => $this->createDownloadList($items, $settings),
'#attached' => [
'library' => [
// Attach the wavesurfer library.
'audiofield/audiofield.' . $this->getPluginLibraryName(),
],
'drupalSettings' => [
'audiofieldwavesurfer' => [
$settings['unique_id'] => $player_settings,
],
],
],
];
}
/**
* {@inheritdoc}
*/
public function getPluginLibraryVersion() {
// Parse the JSON file for version info.
$library_path = $this->fileSystem->realpath(DRUPAL_ROOT . $this->getPluginLibraryPath() . '/package.json');
$library_data = Json::decode(file_get_contents($library_path));
return $library_data['version'];
}
}
@@ -0,0 +1,112 @@
<?php
namespace Drupal\audiofield\Plugin\AudioPlayer;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\audiofield\AudioFieldPluginBase;
/**
* Implements the WordPress Audio Player plugin.
*
* @AudioPlayer (
* id = "wordpress_audio_player",
* title = @Translation("WordPress audio player"),
* description = @Translation("Standalone audio player originally built for WordPress"),
* fileTypes = {
* "mp3",
* },
* libraryName = "wordpress",
* website = "http://wpaudioplayer.com",
* )
*/
class WordPressAudioPlayer extends AudioFieldPluginBase {
/**
* {@inheritdoc}
*/
public function renderPlayer(FieldItemListInterface $items, $langcode, array $settings) {
// Check to make sure we're installed.
if (!$this->checkInstalled()) {
// Show the error.
$this->showInstallError();
// Simply return the default rendering so the files are still displayed.
return $this->renderDefaultPlayer($items, $settings);
}
// Start building settings to pass to the javascript WordPress builder.
$player_settings = [
// WordPress expects this as a 0 - 100 range.
'volume' => ($settings['audio_player_initial_volume'] * 10),
'animate' => ($settings['audio_player_wordpress_animation'] ? 'yes' : 'no'),
'files' => [],
'autoplay' => $settings['audio_player_autoplay'],
];
// Format files for output.
$template_files = $this->getItemRenderList($items, ($settings['audio_player_wordpress_combine_files'] ? 1 : 0));
foreach ($template_files as $renderInfo) {
// Pass settings for the file.
$player_settings['files'][] = [
'file' => $renderInfo->url->toString(),
'title' => $renderInfo->description,
'unique_id' => $renderInfo->id,
];
}
// If we are combining into a single player, make some modifications.
if ($settings['audio_player_wordpress_combine_files']) {
// Wordpress expects comma-deliminated lists
// when using multiple files in a single player.
$wp_files = [];
$wp_titles = [];
foreach ($player_settings['files'] as $wp_file) {
$wp_files[] = $wp_file['file'];
$wp_titles[] = $wp_file['title'];
}
// Redeclare settings with only a single (combined) file.
$player_settings['files'] = [
[
'file' => implode(',', $wp_files),
'title' => implode(',', $wp_titles),
'unique_id' => $player_settings['files'][0]['unique_id'],
],
];
}
return [
'audioplayer' => [
'#theme' => 'audioplayer',
'#plugin_id' => 'wordpress',
'#settings' => $settings,
'#files' => $template_files,
],
'downloads' => $this->createDownloadList($items, $settings),
'#attached' => [
'library' => [
// Attach the WordPress library.
'audiofield/audiofield.' . $this->getPluginLibraryName(),
],
'drupalSettings' => [
'audiofieldwordpress' => [
$this->getUniqueRenderId() => $player_settings,
],
],
],
];
}
/**
* {@inheritdoc}
*/
public function getPluginLibraryVersion() {
// Parse the audio-player.js file for version info.
$library_path = $this->fileSystem->realpath(DRUPAL_ROOT . $this->getPluginLibraryPath() . '/audio-player.js');
$library_data = file_get_contents($library_path);
$matches = [];
preg_match('%SWFObject v([0-9\.]+).*%', $library_data, $matches);
return $matches[1];
}
}
@@ -0,0 +1,657 @@
<?php
namespace Drupal\audiofield\Plugin\Field\FieldFormatter;
use Drupal\audiofield\AudioFieldPlayerManager;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Plugin implementation of audio player file formatter.
*
* @FieldFormatter(
* id = "audiofield_audioplayer",
* label = @Translation("Audiofield Audio Player"),
* field_types = {
* "file", "link"
* }
* )
*/
class AudioFieldFieldFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
/**
* Audio player management service.
*
* @var \Drupal\audiofield\AudioFieldPlayerManager
*/
protected $audioPlayerManager;
/**
* {@inheritdoc}
*/
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, AudioFieldPlayerManager $audio_player_manager) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
$this->audioPlayerManager = $audio_player_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$plugin_id,
$plugin_definition,
$configuration['field_definition'],
$configuration['settings'],
$configuration['label'],
$configuration['view_mode'],
$configuration['third_party_settings'],
$container->get('plugin.manager.audiofield')
);
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
// Get the fieldname in a format that works for all forms.
$fieldname = $this->fieldDefinition->getItemDefinition()->getFieldDefinition()->getName();
// Loop over each plugin type and create an entry for it.
$plugin_definitions = $this->audioPlayerManager->getDefinitions();
$plugins = [
'available' => [],
'unavailable' => [],
];
foreach ($plugin_definitions as $plugin_id => $plugin) {
// Create an instance of the player.
$player = $this->audioPlayerManager->createInstance($plugin_id);
if ($player->checkInstalled()) {
$plugins['available'][$plugin_id] = $plugin['title'];
}
else {
$plugins['unavailable'][$plugin_id] = $plugin['title'];
}
}
ksort($plugins['available']);
// Build settings form for display on the structure page.
$elements = parent::settingsForm($form, $form_state);
$default_player = $this->getSetting('audio_player');
if (isset($plugins['unavailable'][$default_player])) {
$default_player = 'default_mp3_player';
}
// Let user select the audio player.
$elements['audio_player'] = [
'#type' => 'select',
'#title' => $this->t('Select Player'),
'#default_value' => $default_player,
'#options' => $plugins['available'],
];
if (count($plugins['unavailable']) > 0) {
ksort($plugins['unavailable']);
$elements['unavailable'] = [
'#type' => 'details',
'#title' => $this->t('Disabled Players:'),
'#open' => FALSE,
'#disabled' => TRUE,
[
'#type' => '#container',
'#attributes' => [],
'#children' => implode('<br/>', $plugins['unavailable']),
],
];
}
// Settings for jPlayer.
// Only show when jPlayer is the selected audio player.
$jplayer_options = [
'none' => 'None (for styling manually with CSS)',
// Add the circle skin in (special non-standard custom skin for jPlayer).
'audiofield.jplayer.theme_jplayer_circle' => 'jPlayer circle player',
];
// Build the list of jPlayer available skins.
foreach (_audiofield_list_skins('jplayer_audio_player') as $skin) {
$jplayer_options[$skin['library_name']] = $skin['name'];
}
$elements['audio_player_jplayer_theme'] = [
'#type' => 'radios',
'#title' => $this->t('Select jPlayer Skin'),
'#description' => $this->t('jPlayer comes bundled with multiple skins by default. You can install additional skins by placing them in /libraries/jplayer/dist/skin/'),
'#default_value' => $this->getSetting('audio_player_jplayer_theme'),
'#options' => $jplayer_options,
'#states' => [
'visible' => [
':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'jplayer_audio_player'],
],
],
];
// Settings for WaveSurfer.
// Only show when WaveSurfer is the selected audio player.
$elements['audio_player_wavesurfer_combine_files'] = [
'#type' => 'checkbox',
'#title' => $this->t('Combine audio files into a single audio player'),
'#description' => $this->t('By default Wavesurfer displays files individually. This option combines the files into a playlist so only one file shows at a time.'),
'#default_value' => $this->getSetting('audio_player_wavesurfer_combine_files'),
'#states' => [
'visible' => [
':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'wavesurfer_audio_player'],
],
],
];
// Settings for WaveSurfer.
$elements['audio_player_wavesurfer_audiorate'] = [
'#type' => 'number',
'#title' => $this->t('Audio Rate'),
'#description' => $this->t("Speed at which to play audio. Lower number is slower."),
'#default_value' => $this->getSetting('audio_player_wavesurfer_audiorate'),
'#states' => [
'visible' => [
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'wavesurfer_audio_player']],
],
],
];
$elements['audio_player_wavesurfer_autocenter'] = [
'#type' => 'checkbox',
'#title' => $this->t('Auto Center'),
'#description' => $this->t("If a scrollbar is present, center the waveform around the progress."),
'#default_value' => $this->getSetting('audio_player_wavesurfer_autocenter'),
'#states' => [
'visible' => [
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'wavesurfer_audio_player']],
],
],
];
// Let user select the wavesurfer backend.
// @see https://github.com/katspaugh/wavesurfer.js/issues/1382
$elements['audio_player_wavesurfer_backend'] = [
'#type' => 'select',
'#title' => $this->t('Select Backend'),
'#description' => $this->t("WebAudio is the default backend for Wavesurfer. Choose MediaElement if you need to play long audio files. See https://github.com/katspaugh/wavesurfer.js/issues/1382."),
'#options' => [
'WebAudio' => $this->t('WebAudio'),
'MediaElement' => $this->t('MediaElement'),
],
'#default_value' => $this->getSetting('audio_player_wavesurfer_backend'),
'#states' => [
'visible' => [
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'wavesurfer_audio_player']],
],
],
];
$elements['audio_player_wavesurfer_bargap'] = [
'#type' => 'number',
'#title' => $this->t('Bar Gap'),
'#description' => $this->t("The optional spacing between bars of the wave."),
'#default_value' => $this->getSetting('audio_player_wavesurfer_bargap'),
'#states' => [
'visible' => [
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'wavesurfer_audio_player']],
],
],
];
$elements['audio_player_wavesurfer_barheight'] = [
'#type' => 'number',
'#title' => $this->t('Bar Height'),
'#description' => $this->t("Height of the waveform bars. Higher number than 1 will increase the waveform bar heights."),
'#default_value' => $this->getSetting('audio_player_wavesurfer_barheight'),
'#states' => [
'visible' => [
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'wavesurfer_audio_player']],
],
],
];
$elements['audio_player_wavesurfer_barwidth'] = [
'#type' => 'number',
'#title' => $this->t('Bar Width'),
'#description' => $this->t("If specified, the waveform will be drawn like this: ▁ ▂ ▇ ▃ ▅ ▂"),
'#default_value' => $this->getSetting('audio_player_wavesurfer_barwidth'),
'#states' => [
'visible' => [
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'wavesurfer_audio_player']],
],
],
];
$elements['audio_player_wavesurfer_cursorcolor'] = [
'#type' => 'color',
'#title' => $this->t('Cursor Color'),
'#description' => $this->t("The fill color of the cursor indicating the playhead position."),
'#default_value' => $this->getSetting('audio_player_wavesurfer_cursorcolor'),
'#states' => [
'visible' => [
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'wavesurfer_audio_player']],
],
],
];
$elements['audio_player_wavesurfer_cursorwidth'] = [
'#type' => 'number',
'#title' => $this->t('Cursor Width'),
'#description' => $this->t("Width of the cursor indicating the playhead position. Measured in pixels."),
'#default_value' => $this->getSetting('audio_player_wavesurfer_cursorwidth'),
'#states' => [
'visible' => [
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'wavesurfer_audio_player']],
],
],
];
$elements['audio_player_wavesurfer_forcedecode'] = [
'#type' => 'checkbox',
'#title' => $this->t('Force Decode'),
'#description' => $this->t("Force decoding of audio using web audio when zooming to get a more detailed waveform."),
'#default_value' => $this->getSetting('audio_player_wavesurfer_forcedecode'),
'#states' => [
'visible' => [
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'wavesurfer_audio_player']],
],
],
];
$elements['audio_player_wavesurfer_normalize'] = [
'#type' => 'checkbox',
'#title' => $this->t('Normalize'),
'#description' => $this->t("If checked, normalize by the maximum peak instead of 1.0."),
'#default_value' => $this->getSetting('audio_player_wavesurfer_normalize'),
'#states' => [
'visible' => [
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'wavesurfer_audio_player']],
],
],
];
$elements['audio_player_wavesurfer_progresscolor'] = [
'#type' => 'color',
'#title' => $this->t('Progress Color'),
'#description' => $this->t("The fill color of the part of the waveform behind the cursor."),
'#default_value' => $this->getSetting('audio_player_wavesurfer_progresscolor'),
'#states' => [
'visible' => [
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'wavesurfer_audio_player']],
],
],
];
$elements['audio_player_wavesurfer_responsive'] = [
'#type' => 'checkbox',
'#title' => $this->t('Responsive'),
'#description' => $this->t("If checked, resize the waveform, when the window is resized. This is debounced with a 100ms timeout by default."),
'#default_value' => $this->getSetting('audio_player_wavesurfer_responsive'),
'#states' => [
'visible' => [
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'wavesurfer_audio_player']],
],
],
];
$elements['audio_player_wavesurfer_wavecolor'] = [
'#type' => 'color',
'#title' => $this->t('Wave Color'),
'#description' => $this->t("The fill color of the waveform after the cursor."),
'#default_value' => $this->getSetting('audio_player_wavesurfer_wavecolor'),
'#states' => [
'visible' => [
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'wavesurfer_audio_player']],
],
],
];
$elements['audio_player_wavesurfer_use_peakfile'] = [
'#type' => 'checkbox',
'#title' => $this->t('Use Peak File'),
'#description' => $this->t("Peak files are used to speed up waveform display on the client and reduce the load on the server by pre-rendering the waveform. These are stored alongside your audio files and are automatically generated."),
'#default_value' => $this->getSetting('audio_player_wavesurfer_use_peakfile'),
'#states' => [
'visible' => [
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'wavesurfer_audio_player']],
],
],
];
$elements['audio_player_wavesurfer_playnexttrack'] = [
'#type' => 'checkbox',
'#title' => $this->t('Automatically skip to next track'),
'#description' => $this->t("If checked, next track in playlist will auto-play"),
'#default_value' => $this->getSetting('audio_player_wavesurfer_playnexttrack'),
'#states' => [
'visible' => [
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'wavesurfer_audio_player']],
],
],
];
// Settings for WordPress.
// Only show when WordPress is the selected audio player.
$elements['audio_player_wordpress_combine_files'] = [
'#type' => 'checkbox',
'#title' => $this->t('Combine audio files into a single audio player'),
'#description' => $this->t('This can be more difficult to see for the WordPress plugin. Multiple files are represented only by small "next" and "previous" arrows. Unchecking this box causes each file to be rendered as its own player.'),
'#default_value' => $this->getSetting('audio_player_wordpress_combine_files'),
'#states' => [
'visible' => [
':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'wordpress_audio_player'],
],
],
];
$elements['audio_player_wordpress_animation'] = [
'#type' => 'checkbox',
'#title' => $this->t('Animate player?'),
'#description' => $this->t('If unchecked, the player will always remain open with the title visible.'),
'#default_value' => $this->getSetting('audio_player_wordpress_animation'),
'#states' => [
'visible' => [
':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'wordpress_audio_player'],
],
],
];
// Settings for SoundManager.
// Only show when SoundManager is the selected audio player.
$elements['audio_player_soundmanager_theme'] = [
'#type' => 'radios',
'#title' => $this->t('Select SoundManager Skin'),
'#default_value' => $this->getSetting('audio_player_soundmanager_theme'),
'#options' => [
'default' => $this->t('Default theme'),
'player360' => $this->t('360 degree player'),
'barui' => $this->t('Bar UI'),
'inlineplayer' => $this->t('Inline Player'),
'pageplayer' => $this->t('Page Player'),
],
'#states' => [
'visible' => [
':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'soundmanager_audio_player'],
],
],
];
// Settings for multiple players.
$elements['audio_player_initial_volume'] = [
'#type' => 'range',
'#title' => $this->t('Set Initial Volume'),
'#default_value' => $this->getSetting('audio_player_initial_volume'),
'#min' => 0,
'#max' => 10,
'#states' => [
'visible' => [
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'jplayer_audio_player']],
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'mediaelement_audio_player']],
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'projekktor_audio_player']],
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'soundmanager_audio_player']],
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'wavesurfer_audio_player']],
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'wordpress_audio_player']],
],
],
];
// Settings for autoplay.
$elements['audio_player_autoplay'] = [
'#type' => 'checkbox',
'#title' => $this->t('Autoplay on page load'),
'#default_value' => $this->getSetting('audio_player_autoplay'),
'#states' => [
'visible' => [
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'audiojs_audio_player']],
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'default_mp3_player']],
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'jplayer_audio_player']],
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'mediaelement_audio_player']],
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'projekktor_audio_player']],
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'wavesurfer_audio_player']],
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'wordpress_audio_player']],
],
],
];
// Settings for autoplay.
$elements['audio_player_lazyload'] = [
'#type' => 'checkbox',
'#title' => $this->t('Lazy Load audio'),
'#description' => $this->t("This setting causes audio not to be loaded until it is played."),
'#default_value' => $this->getSetting('audio_player_lazyload'),
'#states' => [
'visible' => [
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'audiojs_audio_player']],
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'default_mp3_player']],
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'jplayer_audio_player']],
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'mediaelement_audio_player']],
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'projekktor_audio_player']],
],
],
];
// Settings for download button.
$elements['download_button'] = [
'#type' => 'checkbox',
'#title' => $this->t('Display download button on player'),
'#default_value' => $this->getSetting('download_button'),
'#states' => [
'visible' => [
[':input[name="fields[' . $fieldname . '][settings_edit_form][settings][audio_player]"]' => ['value' => 'default_mp3_player']],
],
],
];
// Setting for optional download link.
$elements['download_link'] = [
'#type' => 'checkbox',
'#title' => $this->t('Display download link below player'),
'#default_value' => $this->getSetting('download_link'),
];
return $elements;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$plugin_definitions = $this->audioPlayerManager->getDefinitions();
$settings = $this->getSettings();
// Show which player we are currently using for the field.
$summary = [
$this->t('Selected player: <strong>@player</strong>', [
'@player' => $plugin_definitions[$settings['audio_player']]['title'],
]),
];
// If this is jPlayer, add those settings.
if ($settings['audio_player'] == 'jplayer_audio_player') {
// Display theme.
$theme = 'None (for styling manually with CSS)';
// If this is the custom jplayer circle theme.
if ($settings['audio_player_jplayer_theme'] == 'audiofield.jplayer.theme_jplayer_circle') {
$theme = 'jPlayer circle player';
}
// Search for the theme we're using.
else {
foreach (_audiofield_list_skins('jplayer_audio_player') as $skin) {
if ($skin['library_name'] == $settings['audio_player_jplayer_theme']) {
$theme = $skin['name'];
}
}
}
$summary[] = $this->t('Skin: <strong>@theme</strong>', [
'@theme' => $theme,
]);
}
// If this is wavesurfer, add those settings.
elseif ($settings['audio_player'] == 'wavesurfer_audio_player') {
$summary[] = $this->t('Combine files into single player? <strong>@combine</strong>', [
'@combine' => ($settings['audio_player_wavesurfer_combine_files'] ? 'Yes' : 'No'),
]);
$summary[] = $this->t('Audio Rate: <strong>@value</strong>', [
'@value' => $settings['audio_player_wavesurfer_audiorate'],
]);
$summary[] = $this->t('Auto Center? <strong>@value</strong>', [
'@value' => ($settings['audio_player_wavesurfer_autocenter'] ? 'Yes' : 'No'),
]);
$summary[] = $this->t('Autoplay next track? <strong>@value</strong>', [
'@value' => ($settings['audio_player_wavesurfer_playnexttrack'] ? 'Yes' : 'No'),
]);
$summary[] = $this->t('Backend: <strong>@value</strong>', [
'@value' => $settings['audio_player_wavesurfer_backend'],
]);
$summary[] = $this->t('Bar Gap: <strong>@value</strong>', [
'@value' => $settings['audio_player_wavesurfer_bargap'],
]);
$summary[] = $this->t('Bar Height: <strong>@value</strong>', [
'@value' => $settings['audio_player_wavesurfer_barheight'],
]);
$summary[] = $this->t('Bar Width: <strong>@value</strong>', [
'@value' => $settings['audio_player_wavesurfer_barwidth'],
]);
$summary[] = $this->t('Cursor Color: <span style="border:1px solid black;height:10px;width:10px;display:inline-block;background:@value;"></span>', [
'@value' => $settings['audio_player_wavesurfer_cursorcolor'],
]);
$summary[] = $this->t('Cursor Width: <strong>@value</strong>', [
'@value' => $settings['audio_player_wavesurfer_cursorwidth'],
]);
$summary[] = $this->t('Force Decode? <strong>@value</strong>', [
'@value' => ($settings['audio_player_wavesurfer_forcedecode'] ? 'Yes' : 'No'),
]);
$summary[] = $this->t('Normalize? <strong>@value</strong>', [
'@value' => ($settings['audio_player_wavesurfer_normalize'] ? 'Yes' : 'No'),
]);
$summary[] = $this->t('Progress Color: <span style="border:1px solid black;height:10px;width:10px;display:inline-block;background:@value;"></span>', [
'@value' => $settings['audio_player_wavesurfer_progresscolor'],
]);
$summary[] = $this->t('Responsive? <strong>@value</strong>', [
'@value' => ($settings['audio_player_wavesurfer_responsive'] ? 'Yes' : 'No'),
]);
$summary[] = $this->t('Wave Color: <span style="border:1px solid black;height:10px;width:10px;display:inline-block;background:@value;"></span>', [
'@value' => $settings['audio_player_wavesurfer_wavecolor'],
]);
$summary[] = $this->t('Use Peak File? <strong>@value</strong>', [
'@value' => ($settings['audio_player_wavesurfer_use_peakfile'] ? 'Yes' : 'No'),
]);
}
// If this is wordpress, add those settings.
elseif ($settings['audio_player'] == 'wordpress_audio_player') {
$summary[] = $this->t('Combine files into single player? <strong>@combine</strong>', [
'@combine' => ($settings['audio_player_wordpress_combine_files'] ? 'Yes' : 'No'),
]);
$summary[] = $this->t('Animate player? <strong>@animate</strong>', [
'@animate' => ($settings['audio_player_wordpress_animation'] ? 'Yes' : 'No'),
]);
}
// If this is soundmanager, add those settings.
elseif ($settings['audio_player'] == 'soundmanager_audio_player') {
$skins = [
'default' => 'Default theme',
'player360' => '360 degree player',
'barui' => 'Bar UI',
'inlineplayer' => 'Inline Player',
'pageplayer' => 'Page Player',
];
$summary[] = $this->t('Skin: <strong>@skin</strong>', [
'@skin' => $skins[$settings['audio_player_soundmanager_theme']],
]);
}
// Show combined settings for multiple players.
if (in_array($settings['audio_player'], [
'jplayer_audio_player',
'mediaelement_audio_player',
'projekktor_audio_player',
'soundmanager_audio_player',
'wavesurfer_audio_player',
'wordpress_audio_player',
])) {
// Display volume.
$summary[] = $this->t('Initial volume: <strong>@volume out of 10</strong>', [
'@volume' => $settings['audio_player_initial_volume'],
]);
}
// Display autoplay.
if (in_array($settings['audio_player'], [
'audiojs_audio_player',
'default_mp3_player',
'jplayer_audio_player',
'mediaelement_audio_player',
'projekktor_audio_player',
'wavesurfer_audio_player',
'wordpress_audio_player',
])) {
$summary[] = $this->t('Autoplay: <strong>@autoplay</strong>', [
'@autoplay' => ($settings['audio_player_autoplay'] ? 'Yes' : 'No'),
]);
}
// Display lazy load.
if (in_array($settings['audio_player'], [
'audiojs_audio_player',
'default_mp3_player',
'jplayer_audio_player',
'mediaelement_audio_player',
'projekktor_audio_player',
])) {
$summary[] = $this->t('Lazy Load: <strong>@lazyload</strong>', [
'@lazyload' => ($settings['audio_player_lazyload'] ? 'Yes' : 'No'),
]);
}
// Check to make sure the library is installed.
$player = $this->audioPlayerManager->createInstance($settings['audio_player']);
if (!$player->checkInstalled()) {
$summary[] = $this->t('<strong style="color:red;">Error: this player library is currently not installed. Please select another player or reinstall the library.</strong>');
}
// Show whether or not we are displaying download buttons.
$summary[] = $this->t('Display download button: <strong>@display_link</strong>', [
'@display_link' => ($settings['download_button'] ? 'Yes' : 'No'),
]);
// Show whether or not we are displaying direct downloads.
$summary[] = $this->t('Display download link: <strong>@display_link</strong>', [
'@display_link' => ($settings['download_link'] ? 'Yes' : 'No'),
]);
return $summary;
}
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'audio_player' => 'default_mp3_player',
'audio_player_jplayer_theme' => 'none',
'audio_player_wavesurfer_combine_files' => FALSE,
'audio_player_wavesurfer_audiorate' => 1,
'audio_player_wavesurfer_autocenter' => TRUE,
'audio_player_wavesurfer_backend' => 'WebAudio',
'audio_player_wavesurfer_bargap' => 0,
'audio_player_wavesurfer_barheight' => 1,
'audio_player_wavesurfer_barwidth' => NULL,
'audio_player_wavesurfer_cursorcolor' => '#333',
'audio_player_wavesurfer_cursorwidth' => 1,
'audio_player_wavesurfer_forcedecode' => FALSE,
'audio_player_wavesurfer_normalize' => FALSE,
'audio_player_wavesurfer_playnexttrack' => TRUE,
'audio_player_wavesurfer_progresscolor' => '#555',
'audio_player_wavesurfer_responsive' => FALSE,
'audio_player_wavesurfer_wavecolor' => '#999',
'audio_player_wavesurfer_use_peakfile' => FALSE,
'audio_player_wordpress_combine_files' => FALSE,
'audio_player_wordpress_animation' => TRUE,
'audio_player_soundmanager_theme' => 'default',
'audio_player_initial_volume' => 8,
'audio_player_autoplay' => FALSE,
'audio_player_lazyload' => FALSE,
'download_button' => FALSE,
'download_link' => FALSE,
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
// Early opt-out if the field is empty.
if (count($items) <= 0) {
return $elements;
}
$plugin_id = $this->getSetting('audio_player');
$player = $this->audioPlayerManager->createInstance($plugin_id);
$elements[] = $player->renderPlayer($items, $langcode, $this->getSettings());
return $elements;
}
}
@@ -0,0 +1,19 @@
{#
/**
* @file
* Default theme implementation for AudioField audioplayer download links.
*
* Available variables:
* - links: downloa
*
* @ingroup themeable
*/
#}
<table class="audiofield-downloads">
<caption>{{ 'Download files:'|t }}</caption>
{% for file in links %}
<tr>
<td class="audiofield-download-link">{{ file.link }}</td>
</tr>
{% endfor %}
</table>
@@ -0,0 +1,40 @@
{#
/**
* @file
* Default theme implementation for Audio.js audio player.
*
* Available variables:
* - plugin_id: the name of the plugin being used for templating.
* - plugin_theme: the name of the specific plugin theme, if it exists.
* - files: array of render info for each file.
* - settings: array of settings for thie player.
*
* @ingroup themeable
*/
#}
<div class="audiofield">
<div id="{{ settings.id }}" class="audiofield-audiojs-frame">
<div class="audiofield-audiojs">
<audio preload="{% if settings.audio_player_lazyload == 1 %}none{% else %}auto{% endif %}" {% if settings.audio_player_autoplay == 1 %} autoplay="autoplay" {% endif %}></audio>
<div class="play-pauseZ">
<p class="playZ"></p>
<p class="pauseZ"></p>
<p class="loadingZ"></p>
<p class="errorZ"></p>
</div>
<div class="scrubberZ">
<div class="progressZ"></div>
<div class="loadedZ"></div>
</div>
<div class="timeZ">
<em class="playedZ">00:00</em>/<strong class="durationZ">00:00</strong>
</div>
<div class="error-messageZ"></div>
</div>
<ol>
{% for file in files %}
<li><a href="#" data-src="{{ file.url }}">{{ file.description }}</a></li>
{% endfor %}
</ol>
</div>
</div>
@@ -0,0 +1,65 @@
{#
/**
* @file
* Multiple file theme implementation for jPlayer audio player.
*
* Available variables:
* - plugin_id: the name of the plugin being used for templating.
* - plugin_theme: the name of the specific plugin theme, if it exists.
* - files: array of render info for each file.
* - settings: array of settings for thie player.
*
* @ingroup themeable
*/
#}
<div class="audiofield">
<div id="jp_container_{{ settings.id }}" class="jp-video jp-video-270p" role="application" aria-label="media player">
<div class="jp-type-playlist">
<div id="jquery_jplayer_{{ settings.id }}" class="jp-jplayer"></div>
<div class="jp-gui">
<div class="jp-interface">
<div class="jp-progress">
<div class="jp-seek-bar">
<div class="jp-play-bar"></div>
</div>
</div>
<div class="jp-current-time" role="timer" aria-label="time">&nbsp;</div>
<div class="jp-duration" role="timer" aria-label="duration">&nbsp;</div>
<div class="jp-controls-holder">
<div class="jp-controls">
<button class="jp-previous" role="button" tabindex="0">{{ 'previous'|t }}</button>
<button class="jp-play" role="button" tabindex="0">{{ 'play'|t }}</button>
<button class="jp-next" role="button" tabindex="0">{{ 'next'|t }}</button>
<button class="jp-stop" role="button" tabindex="0">{{ 'stop'|t }}</button>
</div>
<div class="jp-volume-controls">
<button class="jp-mute" role="button" tabindex="0">{{ 'mute'|t }}</button>
<button class="jp-volume-max" role="button" tabindex="0">{{ 'max volume'|t }}</button>
<div class="jp-volume-bar">
<div class="jp-volume-bar-value"></div>
</div>
</div>
<div class="jp-toggles">
<button class="jp-repeat" role="button" tabindex="0">{{ 'repeat'|t }}</button>
<button class="jp-shuffle" role="button" tabindex="0">{{ 'shuffle'|t }}</button>
<button class="jp-full-screen" role="button" tabindex="0">{{ 'full screen'|t }}</button>
</div>
</div>
<div class="jp-details">
<div class="jp-title" aria-label="title">&nbsp;</div>
</div>
</div>
</div>
<div class="jp-playlist">
<ul>
<!-- The method Playlist.displayPlaylist() uses this unordered list -->
<li>&nbsp;</li>
</ul>
</div>
<div class="jp-no-solution">
<span>{{ 'Update Required'|t }}</span>
To play the media you will need to either update your browser to a recent version or update your <a href="http:// get.adobe.com/flashplayer/" target="_blank">Flash plugin</a>.
</div>
</div>
</div>
</div>
@@ -0,0 +1,53 @@
{#
/**
* @file
* Single file default theme implementation for jPlayer audio player.
*
* Available variables:
* - plugin_id: the name of the plugin being used for templating.
* - plugin_theme: the name of the specific plugin theme, if it exists.
* - files: array of render info for each file.
* - settings: array of settings for thie player.
*
* @ingroup themeable
*/
#}
<div class="audiofield">
<div id="jquery_jplayer_{{ settings.id }}" class="jp-jplayer"></div>
<div id="jp_container_{{ settings.id }}" class="jp-audio" role="application" aria-label="media player">
<div class="jp-type-single">
<div class="jp-gui jp-interface">
<div class="jp-controls">
<button class="jp-play" role="button" tabindex="0">{{ 'play'|t }}</button>
<button class="jp-stop" role="button" tabindex="0">{{ 'stop'|t }}</button>
</div>
<div class="jp-progress">
<div class="jp-seek-bar">
<div class="jp-play-bar"></div>
</div>
</div>
<div class="jp-volume-controls">
<button class="jp-mute" role="button" tabindex="0">{{ 'mute'|t }}</button>
<button class="jp-volume-max" role="button" tabindex="0">{{ 'max volume'|t }}</button>
<div class="jp-volume-bar">
<div class="jp-volume-bar-value"></div>
</div>
</div>
<div class="jp-time-holder">
<div class="jp-current-time" role="timer" aria-label="time">&nbsp;</div>
<div class="jp-duration" role="timer" aria-label="duration">&nbsp;</div>
<div class="jp-toggles">
<button class="jp-repeat" role="button" tabindex="0">{{ 'repeat'|t }}</button>
</div>
</div>
</div>
<div class="jp-details">
<div class="jp-title" aria-label="title">&nbsp;</div>
</div>
<div class="jp-no-solution">
<span>{{ 'Update Required'|t }}</span>
To play the media you will need to either update your browser to a recent version or update your <a href="http:// get.adobe.com/flashplayer/" target="_blank">Flash plugin</a>.
</div>
</div>
</div>
</div>
@@ -0,0 +1,43 @@
{#
/**
* @file
* Default theme implementation for jPlayer audio player.
*
* Available variables:
* - plugin_id: the name of the plugin being used for templating.
* - plugin_theme: the name of the specific plugin theme, if it exists.
* - files: array of render info for each file.
* - settings: array of settings for thie player.
*
* @ingroup themeable
*/
#}
<div class="audiofield">
{% if settings.audio_player_jplayer_theme == 'audiofield.jplayer.theme_jplayer_circle' %}
{% for file in files %}
<div class="audiofield-player">
<div id="jquery_jplayer_{{ file.id }}" class="cp-jplayer"></div>
<div class="cp-circle-frame">
<div id="cp_container_{{ file.id }}" class="cp-container">
<div class="cp-buffer-holder">
<div class="cp-buffer-1"></div>
<div class="cp-buffer-2"></div>
</div>
<div class="cp-progress-holder">
<div class="cp-progress-1"></div>
<div class="cp-progress-2"></div>
</div>
<div class="cp-circle-control"></div>
<ul class="cp-controls">
<li><a class="cp-play" tabindex="1">{{ 'play'|t }}</a></li>
<li><a class="cp-pause" style="display:none;" tabindex="1">{{ 'pause'|t }}</a></li>
</ul>
</div>
<p class="description">{{ file.description }}</p>
</div>
</div>
{% endfor %}
{% endif %}
</div>
@@ -0,0 +1,39 @@
{#
/**
* @file
* Circle theme implementation for jPlayer audio player.
*
* Available variables:
* - plugin_id: the name of the plugin being used for templating.
* - plugin_theme: the name of the specific plugin theme, if it exists.
* - files: array of render info for each file.
* - settings: array of settings for thie player.
*
* @ingroup themeable
*/
#}
<div class="audiofield">
{% for file in files %}
<div class="audiofield-player">
<div id="jquery_jplayer_{{ file.id }}" class="cp-jplayer"></div>
<div class="cp-circle-frame">
<div id="cp_container_{{ file.id }}" class="cp-container">
<div class="cp-buffer-holder">
<div class="cp-buffer-1"></div>
<div class="cp-buffer-2"></div>
</div>
<div class="cp-progress-holder">
<div class="cp-progress-1"></div>
<div class="cp-progress-2"></div>
</div>
<div class="cp-circle-control"></div>
<ul class="cp-controls">
<li><a class="cp-play" tabindex="1">play</a></li>
<li><a class="cp-pause" style="display:none;" tabindex="1">pause</a></li>
</ul>
</div>
<p class="description">{{ file.description }}</p>
</div>
</div>
{% endfor %}
</div>
@@ -0,0 +1,27 @@
{#
/**
* @file
* Default theme implementation for Media Element audio player.
*
* Available variables:
* - plugin_id: the name of the plugin being used for templating.
* - plugin_theme: the name of the specific plugin theme, if it exists.
* - files: array of render info for each file.
* - settings: array of settings for thie player.
*
* @ingroup themeable
*/
#}
<div class="audiofield">
{% for file in files %}
<div class="audiofield-player">
<div class="mediaelementaudio_frame">
<audio id="mediaelement_player_{{ file.id }}" preload="{% if settings.audio_player_lazyload == 1 %}none{% else %}auto{% endif %}" {% if settings.audio_player_autoplay == 1 %} autoplay="autoplay" {% endif %} controls>
<source src="{{ file.url }}">
Your browser does not support the audio element.
</audio>
</div>
<p class="description">{{ file.description }}</p>
</div>
{% endfor %}
</div>
@@ -0,0 +1,25 @@
{#
/**
* @file
* Default theme implementation for Projekktor audio player.
*
* Available variables:
* - plugin_id: the name of the plugin being used for templating.
* - plugin_theme: the name of the specific plugin theme, if it exists.
* - files: array of render info for each file.
* - settings: array of settings for thie player.
*
* @ingroup themeable
*/
#}
<div class="audiofield">
{% for file in files %}
<div class="audiofield-player">
<audio id="{{ file.id }}" preload="{% if settings.audio_player_lazyload == 1 %}none{% else %}auto{% endif %}" class="audiofield-{{ plugin_id }} {{ plugin_id }}" controls>
<source src="{{ file.url }}" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<p class="description">{{ file.description }}</p>
</div>
{% endfor %}
</div>
@@ -0,0 +1,76 @@
{#
/**
* @file
* Bar UI theme implementation for SoundManager audio player.
*
* Available variables:
* - plugin_id: the name of the plugin being used for templating.
* - plugin_theme: the name of the specific plugin theme, if it exists.
* - files: array of render info for each file.
* - settings: array of settings for thie player.
*
* @ingroup themeable
*/
#}
<div class="audiofield">
<div class="sm2-bar-ui {% if settings.count > 1 %} playlist-open {% endif %}">
<div class="bd sm2-main-controls">
<div class="sm2-inline-texture"></div>
<div class="sm2-inline-gradient"></div>
<div class="sm2-inline-element sm2-button-element">
<div class="sm2-button-bd">
<a href="#play" class="sm2-inline-button sm2-icon-play-pause">{{ 'Play / pause'|t }}</a>
</div>
</div>
<div class="sm2-inline-element sm2-inline-status">
<div class="sm2-playlist">
<div class="sm2-playlist-target"><noscript><p>{{ 'JavaScript is required.'|t }}</p></noscript></div>
</div>
<div class="sm2-progress">
<div class="sm2-row">
<div class="sm2-inline-time">0:00</div>
<div class="sm2-progress-bd">
<div class="sm2-progress-track">
<div class="sm2-progress-bar"></div>
<div class="sm2-progress-ball"><div class="icon-overlay"></div></div>
</div>
</div>
<div class="sm2-inline-duration">0:00</div>
</div>
</div>
</div>
<div class="sm2-inline-element sm2-button-element sm2-volume">
<div class="sm2-button-bd">
<span class="sm2-inline-button sm2-volume-control volume-shade"></span>
<a href="#volume" class="sm2-inline-button sm2-volume-control">{{ 'volume'|t }}</a>
</div>
</div>
<div class="sm2-inline-element sm2-button-element sm2-menu">
<div class="sm2-button-bd">
<a href="#menu" class="sm2-inline-button sm2-icon-menu">{{ 'menu'|t }}</a>
</div>
</div>
</div>
<div class="bd sm2-playlist-drawer sm2-element">
<div class="sm2-playlist-wrapper">
<ul class="sm2-playlist-bd">
{% for file in files %}
<li>
<a href="{{ file.url }}">{{ file.description }}</a>
</li>
{% endfor %}
</ul>
</div>
<div class="sm2-extra-controls">
<div class="bd">
<div class="sm2-inline-element sm2-button-element">
<a href="#prev" title="Previous" class="sm2-inline-button previous">&lt; {{ 'previous'|t }}</a>
</div>
<div class="sm2-inline-element sm2-button-element">
<a href="#next" title="Next" class="sm2-inline-button next">&gt; {{ 'next'|t }}</a>
</div>
</div>
</div>
</div>
</div>
</div>
@@ -0,0 +1,23 @@
{#
/**
* @file
* Inline player theme implementation for SoundManager audio player.
*
* Available variables:
* - plugin_id: the name of the plugin being used for templating.
* - plugin_theme: the name of the specific plugin theme, if it exists.
* - files: array of render info for each file.
* - settings: array of settings for thie player.
*
* @ingroup themeable
*/
#}
<div class="audiofield">
{% for file in files %}
<ul class="graphic">
<li>
<a href="{{ file.url }}">{{ file.description }}</a>
</li>
</ul>
{% endfor %}
</div>
@@ -0,0 +1,23 @@
{#
/**
* @file
* Inline player theme implementation for SoundManager audio player.
*
* Available variables:
* - plugin_id: the name of the plugin being used for templating.
* - plugin_theme: the name of the specific plugin theme, if it exists.
* - files: array of render info for each file.
* - settings: array of settings for thie player.
*
* @ingroup themeable
*/
#}
<div class="audiofield">
{% for file in files %}
<ul class="playlist">
<li>
<a href="{{ file.url }}">{{ file.description }}</a>
</li>
</ul>
{% endfor %}
</div>
@@ -0,0 +1,21 @@
{#
/**
* @file
* Player 360 theme implementation for SoundManager audio player.
*
* Available variables:
* - plugin_id: the name of the plugin being used for templating.
* - plugin_theme: the name of the specific plugin theme, if it exists.
* - files: array of render info for each file.
* - settings: array of settings for thie player.
*
* @ingroup themeable
*/
#}
<div class="audiofield">
{% for file in files %}
<div class="ui360">
<a href="{{ file.url }} ">{{ file.description }}</a>
</div>
{% endfor %}
</div>
@@ -0,0 +1,24 @@
{#
/**
* @file
* Default theme implementation for SoundManager audio player.
*
* Available variables:
* - plugin_id: the name of the plugin being used for templating.
* - plugin_theme: the name of the specific plugin theme, if it exists.
* - files: array of render info for each file.
* - settings: array of settings for thie player.
*
* @see template_preprocess_audioplayer__soundmanager()
*
* @ingroup themeable
*/
#}
<div class="audiofield">
{% for file in files %}
<div id="audiofield-audio-player-{{ file.id }}" class="soundmanageraudio_frame">
<a href="{{ file.url }}" class="sm2_button">{{ file.description }}</a>
<p class="description">{{ file.description }}</p>
</div>
{% endfor %}
</div>
@@ -0,0 +1,29 @@
{#
/**
* @file
* Playlist theme implementation for Wavesurfer audio player.
*
* Available variables:
* - plugin_id: the name of the plugin being used for templating.
* - plugin_theme: the name of the specific plugin theme, if it exists.
* - files: array of render info for each file.
* - settings: array of settings for thie player.
*
* @ingroup themeable
*/
#}
<div class="audiofield">
<div class="audiofield-wavesurfer playlist" id="wavesurfer_playlist-{{ settings.unique_id }}">
<div class="waveform"></div>
<div class="player-button previous">{{ 'Previous'|t }}</div>
<div class="player-button playpause play">{{ 'Play'|t }}</div>
<div class="player-button next">{{ 'Next'|t }}</div>
<input type="range" class="volume" min="0" max="10" value="{{ settings.audio_player_initial_volume }}">
<div class="playing">{{ 'Playing'|t }}:</div>
<ol class="playlist">
{% for file in files %}
<li class="track" data-src="{{ file.url }}" data-peakpath="{{ file.peakpath }}">{{ file.description }}</li>
{% endfor %}
</ol>
</div>
</div>
@@ -0,0 +1,24 @@
{#
/**
* @file
* Default theme implementation for Wavesurfer audio player.
*
* Available variables:
* - plugin_id: the name of the plugin being used for templating.
* - plugin_theme: the name of the specific plugin theme, if it exists.
* - files: array of render info for each file.
* - settings: array of settings for thie player.
*
* @ingroup themeable
*/
#}
<div class="audiofield">
{% for file in files %}
<div class="audiofield-wavesurfer" id="{{ file.id }}">
<div id="audiofield-audio-player-{{ file.id }}" class="waveform"></div>
<div class="player-button playpause play">{{ 'Play'|t }}</div>
<input type="range" class="volume" min="0" max="10" value="{{ settings.audio_player_initial_volume}}">
<p class="description">{{ file.description }}</p>
</div>
{% endfor %}
</div>
@@ -0,0 +1,21 @@
{#
/**
* @file
* Default theme implementation for Wordpress audio player.
*
* Available variables:
* - plugin_id: the name of the plugin being used for templating.
* - plugin_theme: the name of the specific plugin theme, if it exists.
* - files: array of render info for each file.
* - settings: array of settings for thie player.
*
* @ingroup themeable
*/
#}
<div class="audiofield">
{% for file in files %}
<div class="wordpressaudio_frame">
<div class="wordpressaudioplayer" id="wordpressaudioplayer_{{ file.id }}">{{ file.description }}</div>
</div>
{% endfor %}
</div>
@@ -0,0 +1,25 @@
{#
/**
* @file
* Default implementation for Audiofield audio players.
*
* Available variables:
* - plugin_id: the name of the plugin being used for templating.
* - plugin_theme: the name of the specific plugin theme, if it exists.
* - files: array of render info for each file.
* - settings: array of settings for thie player.
*
* @ingroup themeable
*/
#}
<div class="audiofield">
{% for file in files %}
<div class="audiofield-player">
<audio id="audiofield-audio-player-{{ file.id }}" preload="{% if settings.audio_player_lazyload == 1 %}none{% else %}auto{% endif %}" controls {% if settings.audio_player_autoplay == 1 %} autoplay {% endif %} {% if settings.download_button != 1 %} controlsList="nodownload" {% endif %}>
<source src="{{ file.url }}" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<p class="description">{{ file.description }}</p>
</div>
{% endfor %}
</div>