【发布时间】:2021-08-12 12:55:27
【问题描述】:
使用 CPT“有声书”处理 Wordpress 项目,在前端视图中的每个有声书帖子页面上,它都有一个 mp3 播放器。
因为有这么多的音频文件,而不是从管理员将每个音频附加到其所属的帖子,我想知道如何制作一个可以自动识别正确文件名并使其可用于前端的 php 函数。
所有的音频文件都按照相同的规则命名:
{Category#}-{Story#}-{VoiceOverArtist}_{otherText}.mp3
C{#}-S{#}-{NAME}_{other_text}.mp3 其中“other_text”部分是可选的
音频文件名如下:
[音频文件夹]
- C1-S1-Jason_slow.mp3
- C1-S25-Jenny_revision2.mp3
- C2-S43-Jason.mp3
- C4-S99-Thomas_with_background_music.mp3
在单音频 CPT 模板中, 我想要一个 php 函数“get_audio_file($category, $story_id)”。
理想情况下:
<?= get_audio_file("C1", "S25"); ?>
会输出“C1-S25-Jenny_revision2.mp3”,并且
<?= get_audio_file("C4", "S99"); ?>
将输出“C4-S99-Thomas_with_background_music.mp3”
我还想要识别配音艺术家姓名的功能,这样我以后可以使用一个数组来交叉引用它,并在音频帖子页面中显示粉红色或蓝色以指示配音艺术家的性别。
这是我目前在 PHP 知识有限的情况下所做的工作:
function get_audio_file($category, $story_id) {
// Define the root folder of the audio files
$upload_dir = wp_upload_dir();
$dir = $upload_dir['baseurl'] . '/story/audio';
// Saw this from other question.. not sure how to implement it with regular expression
$files = glob($dir.'/*.mp3');
$artist = {artist_name}; //this part I have no clue how to grab the artist name into the variable.
// Getting the filename prefix, eg: C1-S5-{artist}-{suffix}
// suffix is optional, might not exist
$filename_prefix = $category . "-" . $story_id;
if ( !empty( $suffix ) {
$filename = $filename_prefix . "-" . $artist . "_" . $suffix;
} else {
$filename = $filename_prefix . "-" . $artist;
}
// Put the voice artist name into gender-based array
$female_artist = array("Jenny", "Sabrina"...);
$male_artist = array("Jason", "Tom", "Thomas"...);
// This determine the gender of the voice artist
if ( in_array( $artist, $female_artist ) ) {
$gender = "female";
} elseif ( in_array( $artist, $fale_artist ) ) {
$gender ="male";
} else {
$gender = "null";
}
}
return $filename;
我完全失去的部分是如何使用正则表达式将正确的值分配给文件名变量......
有人可以指导我吗
【问题讨论】: