Jquery AJAX POST 返回错误 500 - Google 文本转语音模块

发布于 2025-01-13 06:49:56 字数 6967 浏览 2 评论 0原文

我有一个使用谷歌 API 制作的文本到语音模块,但是,它曾经工作正常(将用户输入的文本转换为语音)。但从昨天开始,我在 Jquery Ajax POST 中遇到了这个错误,在控制台中显示错误 500。

代码如下: 索引页代码:

//在输入字段中添加文本后单击发言按钮

$('#speak').click(function (e) {

        let _speakBtn = $(this);
        // prevent double click
        if (_speakBtn.attr('disabled')){
            return false;
        }
        _speakBtn.attr('disabled','disabled');

        // validate is content not empty
        if ($("#content").val().length < 1 || $.trim($("#content").val()) === ''){
            $("#content").addClass('is-invalid');
            _speakBtn.prop('disabled',false);
            return false;

        }else{
            $("#content").removeClass('is-invalid');
        }

        // validate is language not empty
        if ($("#language").val().length !== 5 || $.trim($("#language").val()) === ''){
            $("#language").addClass('is-invalid');
            _speakBtn.prop('disabled',false);
            return false;

        }else{
            $("#language").removeClass('is-invalid');
        }

        // validate is voice quality not empty
        if (($("#voice_quality").val() !== 'WaveNet' && $("#voice_quality").val() !== 'Standard') || $.trim($("#voice_quality").val()) === ''){
            $("#voice_quality").addClass('is-invalid');
            _speakBtn.prop('disabled',false);
            return false;

        }else{
            $("#voice_quality").removeClass('is-invalid');
        }

        // validate is gender not empty
        if (($("#gender").val() !== 'Female' && $("#gender").val() !== 'Male') || $.trim($("#gender").val()) === ''){
            $("#gender").addClass('is-invalid');
            _speakBtn.prop('disabled',false);
            return false;

        }else{
            $("#gender").removeClass('is-invalid');
        }

        // validate is artist not empty
        if ($("#artist_name").val().length < 2 || $.trim($("#artist_name").val()) === ''){
            $("#artist_name").addClass('is-invalid');
            _speakBtn.prop('disabled',false);
            return false;

        }else{
            $("#artist_name").removeClass('is-invalid');
        }

        $.post('<?= rtrim(TTS_APP_BASE_URL,'/') ?>/ajax.php', $('.ajax_post').serialize(), function (_response) {
            try {
                _response = JSON.parse(_response);
                if (_response.success){
                    //download audio _response.data.link
                    $('#downloadBtn').attr('data-toggle', 'modal');
                    $('#downloadForm').attr('action', _response.data.down_link);

                    //play audio
                    $('#rk_player').prop('hidden', false);
                    $('#rk_player #rk_source').attr('src', _response.data.play_link);
                    $('#rk_player').get(0).load();
                    $('#rk_player').get(0).play();
                }else{
                    alert(_response.message);
                }
            }catch (e) {
                console.error(e);
            }
            _speakBtn.prop('disabled',false);
        });
    });

在上面的表单中,错误发生在 $.post('/ajax.php', $('.ajax_post').serialize(), function (_response) { 行,因为数据未发布到 ajax.php

Ajax.PHP 代码:

/*
if($_SERVER['REQUEST_METHOD'] !== 'POST'){
    http_response_code(404);
    die();
}
*/
    define('HAS_ACCESS', TRUE);
    
    require_once 'tts_app.php';

tts_app.php 代码如下:

//disable direct access to this file
defined('HAS_ACCESS') or die('silence is golden');


require 'partials/bootstrap.php';

use Classes\HandleResponseClass;
use Google\Cloud\TextToSpeech\V1\AudioConfig;
use Google\Cloud\TextToSpeech\V1\AudioEncoding;
use Google\Cloud\TextToSpeech\V1\SynthesisInput;
use Google\Cloud\TextToSpeech\V1\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\VoiceSelectionParams;

// Authenticating with keyfile data.
/*echo "<br>";
print_r( $_ENV);
exit();*/

require_once 'config.php';

$text           = trim($_POST['text']);
$language_code  = trim($_POST['language']);
$voiceList      = TTS_APP_VOICES_LIST;
$selectLanguage = isset($voiceList[$language_code]) ? $voiceList[$language_code]:'';
$artisteName    = trim($_POST['artist_name']);
$gender         = trim($_POST['gender']);
if(empty($_POST['rate'])) {
$rate           = 1;
} else {
$rate           = $_POST['rate'];
}
if(empty($_POST['pitch'])) {
$pitch          = 1;
} else {
$pitch          = $_POST['pitch'];
}

$voice_quality  = $_POST['voice_quality'];
$u_id           = $_POST['u_id'];


// validate request
if (empty($text) || empty($selectLanguage) || empty($voice_quality) || empty($gender) || empty($artisteName) || empty($rate) || empty($pitch)){
    $response['success']    = false;
    $response['message']    = 'Required fields are empty';
    $response['data']       = [];
    echo json_encode($response);
    exit();
}

$textToSpeechClient = new TextToSpeechClient();
$input = new SynthesisInput();
$input->setText($text);
$voice = new VoiceSelectionParams();
$voice->setLanguageCode($language_code);

if (!empty($artisteName)){
    $voice->setName($artisteName);
}
if (!empty($gender)){
    $voice->setSsmlGender($gender == 'Female' ? 2:1);
}
$audioConfig = new AudioConfig();

if (!empty($rate)){
    $audioConfig->setSpeakingRate($rate);
}
if (!empty($pitch)){
    $audioConfig->setPitch($pitch);
}

$audioConfig->setAudioEncoding($voice_quality == 'WaveNet' ? AudioEncoding::OGG_OPUS:AudioEncoding::MP3);

$resp = $textToSpeechClient->synthesizeSpeech($input, $voice, $audioConfig);

// handle response file

$responseClass = new HandleResponseClass($resp);

$responseClass->saveFiles(TTS_APP_BASE_PATH);


/*=-=-= sending response -=-=-*/
$response = [
    'success'   => false,
    'message'   => 'something went wrong, please check your internet connection and try again later',
    'data'      => [],
];

if($responseClass->fileSaved()) {
    $response['success']    = true;
    $response['message']    = '';
    $response['data']       = [
        'down_link' => rtrim(TTS_APP_BASE_URL,'/').'/download.php?file='.urlencode($responseClass->getFileName()),
        'play_link' => rtrim(TTS_APP_BASE_URL,'/').'/'.$responseClass->getDirName().'/'.$responseClass->getFileName().'.mp3',
    ];
    echo json_encode($response);
    exit();
}

echo json_encode($response);
exit();

我收到的错误:

jquery-3.5.1.min.js:2          POST https://vdofy.com/tts-test/ajax.php 500
  send @ jquery-3.5.1.min.js:2
  ajax @ jquery-3.5.1.min.js:2
  S.<computed> @ jquery-3.5.1.min.js:2
  (anonymous) @ index?content_get= Test to speech tesing:1496
  dispatch @ jquery-3.5.1.min.js:2
  v.handle @ jquery-3.5.1.min.js:2

不知道为什么会收到此错误,因为自发布以来我没有更改任何内容工作正常。 请分享您对可能出现问题的想法。

I have a text to speech module made using google's API, However, it used to work fine (converting user-entered text to speech). But since yesterday I come across this error at Jquery Ajax POST showing error 500 in the console.

The Code goes as :
Index Page code:

//On click of speak button after adding text in input fields

$('#speak').click(function (e) {

        let _speakBtn = $(this);
        // prevent double click
        if (_speakBtn.attr('disabled')){
            return false;
        }
        _speakBtn.attr('disabled','disabled');

        // validate is content not empty
        if ($("#content").val().length < 1 || $.trim($("#content").val()) === ''){
            $("#content").addClass('is-invalid');
            _speakBtn.prop('disabled',false);
            return false;

        }else{
            $("#content").removeClass('is-invalid');
        }

        // validate is language not empty
        if ($("#language").val().length !== 5 || $.trim($("#language").val()) === ''){
            $("#language").addClass('is-invalid');
            _speakBtn.prop('disabled',false);
            return false;

        }else{
            $("#language").removeClass('is-invalid');
        }

        // validate is voice quality not empty
        if (($("#voice_quality").val() !== 'WaveNet' && $("#voice_quality").val() !== 'Standard') || $.trim($("#voice_quality").val()) === ''){
            $("#voice_quality").addClass('is-invalid');
            _speakBtn.prop('disabled',false);
            return false;

        }else{
            $("#voice_quality").removeClass('is-invalid');
        }

        // validate is gender not empty
        if (($("#gender").val() !== 'Female' && $("#gender").val() !== 'Male') || $.trim($("#gender").val()) === ''){
            $("#gender").addClass('is-invalid');
            _speakBtn.prop('disabled',false);
            return false;

        }else{
            $("#gender").removeClass('is-invalid');
        }

        // validate is artist not empty
        if ($("#artist_name").val().length < 2 || $.trim($("#artist_name").val()) === ''){
            $("#artist_name").addClass('is-invalid');
            _speakBtn.prop('disabled',false);
            return false;

        }else{
            $("#artist_name").removeClass('is-invalid');
        }

        $.post('<?= rtrim(TTS_APP_BASE_URL,'/') ?>/ajax.php', $('.ajax_post').serialize(), function (_response) {
            try {
                _response = JSON.parse(_response);
                if (_response.success){
                    //download audio _response.data.link
                    $('#downloadBtn').attr('data-toggle', 'modal');
                    $('#downloadForm').attr('action', _response.data.down_link);

                    //play audio
                    $('#rk_player').prop('hidden', false);
                    $('#rk_player #rk_source').attr('src', _response.data.play_link);
                    $('#rk_player').get(0).load();
                    $('#rk_player').get(0).play();
                }else{
                    alert(_response.message);
                }
            }catch (e) {
                console.error(e);
            }
            _speakBtn.prop('disabled',false);
        });
    });

In the above form the error occured at $.post('<?= rtrim(TTS_APP_BASE_URL,'/') ?>/ajax.php', $('.ajax_post').serialize(), function (_response) { line as the data is not being posted to ajax.php

The Ajax.PHP code :

/*
if($_SERVER['REQUEST_METHOD'] !== 'POST'){
    http_response_code(404);
    die();
}
*/
    define('HAS_ACCESS', TRUE);
    
    require_once 'tts_app.php';

tts_app.php code goes as:

//disable direct access to this file
defined('HAS_ACCESS') or die('silence is golden');


require 'partials/bootstrap.php';

use Classes\HandleResponseClass;
use Google\Cloud\TextToSpeech\V1\AudioConfig;
use Google\Cloud\TextToSpeech\V1\AudioEncoding;
use Google\Cloud\TextToSpeech\V1\SynthesisInput;
use Google\Cloud\TextToSpeech\V1\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\VoiceSelectionParams;

// Authenticating with keyfile data.
/*echo "<br>";
print_r( $_ENV);
exit();*/

require_once 'config.php';

$text           = trim($_POST['text']);
$language_code  = trim($_POST['language']);
$voiceList      = TTS_APP_VOICES_LIST;
$selectLanguage = isset($voiceList[$language_code]) ? $voiceList[$language_code]:'';
$artisteName    = trim($_POST['artist_name']);
$gender         = trim($_POST['gender']);
if(empty($_POST['rate'])) {
$rate           = 1;
} else {
$rate           = $_POST['rate'];
}
if(empty($_POST['pitch'])) {
$pitch          = 1;
} else {
$pitch          = $_POST['pitch'];
}

$voice_quality  = $_POST['voice_quality'];
$u_id           = $_POST['u_id'];


// validate request
if (empty($text) || empty($selectLanguage) || empty($voice_quality) || empty($gender) || empty($artisteName) || empty($rate) || empty($pitch)){
    $response['success']    = false;
    $response['message']    = 'Required fields are empty';
    $response['data']       = [];
    echo json_encode($response);
    exit();
}

$textToSpeechClient = new TextToSpeechClient();
$input = new SynthesisInput();
$input->setText($text);
$voice = new VoiceSelectionParams();
$voice->setLanguageCode($language_code);

if (!empty($artisteName)){
    $voice->setName($artisteName);
}
if (!empty($gender)){
    $voice->setSsmlGender($gender == 'Female' ? 2:1);
}
$audioConfig = new AudioConfig();

if (!empty($rate)){
    $audioConfig->setSpeakingRate($rate);
}
if (!empty($pitch)){
    $audioConfig->setPitch($pitch);
}

$audioConfig->setAudioEncoding($voice_quality == 'WaveNet' ? AudioEncoding::OGG_OPUS:AudioEncoding::MP3);

$resp = $textToSpeechClient->synthesizeSpeech($input, $voice, $audioConfig);

// handle response file

$responseClass = new HandleResponseClass($resp);

$responseClass->saveFiles(TTS_APP_BASE_PATH);


/*=-=-= sending response -=-=-*/
$response = [
    'success'   => false,
    'message'   => 'something went wrong, please check your internet connection and try again later',
    'data'      => [],
];

if($responseClass->fileSaved()) {
    $response['success']    = true;
    $response['message']    = '';
    $response['data']       = [
        'down_link' => rtrim(TTS_APP_BASE_URL,'/').'/download.php?file='.urlencode($responseClass->getFileName()),
        'play_link' => rtrim(TTS_APP_BASE_URL,'/').'/'.$responseClass->getDirName().'/'.$responseClass->getFileName().'.mp3',
    ];
    echo json_encode($response);
    exit();
}

echo json_encode($response);
exit();

The error I m getting :

jquery-3.5.1.min.js:2          POST https://vdofy.com/tts-test/ajax.php 500
  send @ jquery-3.5.1.min.js:2
  ajax @ jquery-3.5.1.min.js:2
  S.<computed> @ jquery-3.5.1.min.js:2
  (anonymous) @ index?content_get= Test to speech tesing:1496
  dispatch @ jquery-3.5.1.min.js:2
  v.handle @ jquery-3.5.1.min.js:2

Not sure why am I getting this error as I have not changed anything since it was working fine.
Please share your thoughts on what could have gone wrong.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

晌融 2025-01-20 06:49:56

响应代码 500 是服务器端错误,因此请检查服务器端 PHP 代码中的错误、检查错误日志或打开 php 错误报告以查找导致错误的原因。

Response code 500 is a server side error, So check for errors in your server side PHP code, check error logs or turn on php error reporting to find what is causing the error.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文