Have the JS function defined in your page, with a parameter for the song source:
function song(entry){
mySong.src=entry;
mySong.play();
document.getElementById("p2").innerHTML="Now Playing: " + entry;
}
In your PHP, you'll most likely want to echo a link to play each of the songs inside that folder, right?
Do this:
<?php
//Header("content-type: application/x-javascript");
if ($handle = opendir('/wamp/www/songs/')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo '<a href="javascript:void(0)" onclick="song(\'' . $entry . '\')">' . $entry . '</a><br />';
}
}
closedir($handle);
}
?>
Note that this will show the file's path name with extension, for better display you'd just have to do some string manipulation with php/js substr
/substring
and explode
/split
.
Alright, I rewrote the code to work with your given example:
JS (head)
function song(entry){
var mySong=document.getElementById("song1");
mySong.src=entry;
mySong.play();
document.getElementById("p2").innerHTML="Now Playing: " + entry;
}
PHP + HTML (body)
<?php
//Header("content-type: application/x-javascript");
$path = '/wamp/www/songs/';
if ($handle = opendir($path)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo '<a href="javascript:void(0)" onclick="song(\'' . $path . $entry . '\')">' . $entry . '</a><br />';
}
}
closedir($handle);
}
?>
<p id="p2"></p>
<audio id="song1" controls="controls">
<source src="" type="audio/mpeg" />
</audio>
This will work for mp3 files played in browsers with HTML5 support.
Note that Firefox doesn't support .mp3 playback inside <audio>
tags, see: Why doesn't Firefox support the MP3 file format in <audio>
Thus this solution (with your <audio>
) will give satisfying results in Chrome only (not tested on opera and safari). You may want to fallback to another solution for more compatibility.
If you want compatibility with IE and Firefox, you can try using an <embed>
:
JS
function song(entry){
var mySong=document.createElement('embed');
mySong.src=entry;
mySong.width='250px';
mySong.height='60px';
document.getElementById("song1").innerHTML= '';
document.getElementById("song1").appendChild(mySong);
document.getElementById("p2").innerHTML="Now Playing: " + entry;
}
PHP + HTML
<?php
//Header("content-type: application/x-javascript");
$path = '/wamp/www/songs/';
if ($handle = opendir($path)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo '<a href="javascript:void(0)" onclick="song(\'' . $path . $entry . '\')">' . $entry . '</a><br />';
}
}
closedir($handle);
}
?>
<p id="p2"></p>
<div id="song1"></div>
This will be effectively cross-browser, but may request a plugin installation for Firefox.