Create WAV file for each record in database

问题: I have table in database in which I'm storing wav files in longblob column. I'm trying to create an folder and store all wav's of given user on the server. What I have so f...

问题:

I have table in database in which I'm storing wav files in longblob column. I'm trying to create an folder and store all wav's of given user on the server. What I have so far is query to database and table and so far simple example of storing just one wav. I'm not much familiar with PHP and I'll need a little bit help on this.

$con=mysqli_connect("localhost","root","xxxx","testDB");

if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="SELECT recording FROM users WHERE accountID = '1234'";
$result=mysqli_query($con,$sql);

while ($result = mysqli_fetch_array($row)) {

    $data = $result["recording"];

    //mkdir('/var/spool/sounds/', 0755, true);

    $wavFileName = "/var/spool/sounds/wavfile.wav";
    $fh = fopen($wavFileName, 'w'); 
    fwrite($fh, $data);
    fclose($fh);
}

The snipped above is creating one wav in that directory.

If user has 5 saved wav files, how to create directory with name userID and file1.wav, file2.wav .. etc inside?


回答1:

Just create the path and filename with concatenation of userid and number of files already created. Then, check if that path exists, otherwise create it.

$directory = "/var/spool/sounds/" . $userID;
$fileExtension = ".wav";
$fileNumber = 1;
while ($result = mysqli_fetch_array($row))
{
    $data = $result["recording"];
    if (!is_dir($directory))
        mkdir($directory, 0755, true);

    $wavFileName = $directory . "/file" . $fileNumber;
    /*
     *  if you need to check if the file already exists,
     *  you can rename the new file "/var/spool/sounds/userId/file1_copy.wav"
     *  or "/var/spool/sounds/userId/file1_copy_copy.wav" if a copy already exists and so on.
     */
    while (file_exists($wavFileName . $fileExtension))
        $wavFileName .= "_copy";
    $fh = fopen($wavFileName . $fileExtension, 'w'); 
    fwrite($fh, $data);
    fclose($fh);
    $fileNumber++;
}

回答2:

With the following code, will work :

$account_id = 1234;
mkdir('/var/spool/sounds/'.$account_id, 0755, true);
$sql="SELECT recording FROM users WHERE accountID = ".$account_id ;
$result=mysqli_query($con,$sql);
$i=0;
while ($result = mysqli_fetch_array($row)) {
    $i++;
    $data = $result["recording"];

    $wavFileName = "/var/spool/sounds/".$account_id."/file".$i.".wav";
    $fh = fopen($wavFileName, 'w'); 
    fwrite($fh, $data);
    fclose($fh);
}
  • 发表于 2018-07-13 23:38
  • 阅读 ( 271 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除