问题
I have stored small 100kb mp3 files in mysql db as blob using phpMyAdmin
However i am unable to output it on html and play the audio...here is my code
require ('mysqli_connect.php'); //contains database connection
$sql="SELECT sound FROM english WHERE eWord LIKE '%" . $name . "%' OR kWord LIKE '%" . $name ."%'";
while($row=mysql_fetch_array($result)){
$sound=$row['sound'];
echo '<audio controls>';
echo '<source src="data:audio/mp3;base64,'.$row['sound'].'">';
echo '</audio>';
What actually happens is that on loading the page in xampp localhost grayed out html audio player comes and doesn't play anything
Here is how blob looks in my phpMyAdmin
回答1:
You are trying to set your audio source as a data uri and in the it you specify the data is base64 encoded but use binary data.
You'll have to convert that to base64 encoded data
echo '<source src="data:audio/mpeg;base64,'.base64_encode($row['sound']).'">';
回答2:
the correct form is the following::
<audio controls="controls" preload="metadata" autoplay>
<source src="data:audio/mpeg;base64,<?php echo base64_encode($row['audio']); ?>"/>;
</audio>
just change the name of the column that contains
回答3:
Aside from your database not returning correct data in the blob, try this:
function processmusic($song){
global $db_user, $db_password, $db_name, $db_host;
$dsn = 'mysql:dbname='.$db_name.';host='.$db_host.'';
try {
$db = new PDO($dsn, $db_user, $db_password);
} catch (PDOException $e) {
return 'Connection failed: ' . $e->getMessage();
}
if (($result = $db->query('SELECT music FROM music WHERE `name` = "'.$song.'"')) !== false) {
return '<div content="Content-Type: audio/mp3">
<audio controls="controls" preload="metadata" autoplay>
<source src="data:audio/mp3;base64,'.base64_encode($result->fetch(PDO::FETCH_COLUMN)).'"/>;
</audio>
</div>';
} else {
// actions to take if it fails
}
}
I found the PDO method worked for video and audio whereas without it I had nothing but issues. My only problem with this is I can't skip to time in the song. It plays but the timer is at the far right counting up. This is a limitation of the browser I am using after some trial and error.
回答4:
Try this.
<?php
include 'connect.php';
$id=1 //id of the music file
$query = mysqli_query($con,"SELECT content FROM music WHERE id='$id'");
$row = mysqli_fetch_assoc($query);
header("Content-type: audio/mp3");
header("Content-transfer-encoding:binary");
header("Accept-Ranges:bytes");
echo $row['content'];
?>
This worked for me!!!!
来源:https://stackoverflow.com/questions/35623814/how-to-play-mp3-audio-stored-im-mysql-blob-using-php