简体   繁体   中英

How to stream audio files without giving absolute path

Is there anyway to stream an audio file without giving complete path of the file.

For example whenever we tried to play mp3 file with HTML5 Audio tag or With javascript, then i have to supply complete path of mp3 file something like this

<audio controls>
  <source src="http://example.com/file/hello_name.mp3" type="audio/mpeg">
</audio>

So, i think can we supply an id of the mp3 file instead of complete path of the file which should be something like this:

<audio controls>
  <source src="http://example.com/stream.php?file_id=111" type="audio/mpeg">
</audio>

Typically you'd have stream.php deliver the binary data (eg for file_id == 111 as in your example) by sending the correct headers with header() and the data with readfile() provided that you have a relation between file_id and a physical file in a database or something similar.

Please be careful with readfile() , though, and be aware that it will just output whatever it's told to, so make sure your application doesn't allow someone to tell it to output other stuff like config files with database passwords and such.

Your stream.php file will look like this:

<?php
    // Say you hava a table "file_paths" with two columns file_id and file_path
    $sql = $pdo->prepare("SELECT FROM file_paths WHERE file_id = ?");
    $sql->bindValue(1, $_GET['file_id'], PDO::PARAM_INT);
    $sql->execute();
    $fetch = $sql->fetchObject();

    // retrieve file path using its id
    $path = $fetch->file_path;
    header("Location: " . $path);
?>

And then on target page, add the player by passing file_id to stream.php like this:

<audio controls>
  <source src="stream.php?file_id=123" type="audio/mpeg">
</audio>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM