首页 > 解决方案 > 我确实知道如何解决语言/音频问题,但我不知道如何将它组合成代码

问题描述

这是我的代码:

$(document).ready(function() {
$(document).on("click", ".audioButton", function() {
var word = $(this).parent().find('.exerciseWord').html().toLowerCase() + '.mp3';
play(word);
});
getFileArray(); // load on page load
});

function getFileArray(word) {
$.getJSON("https://test.diglin.eu/api/media/fileList", {
  lang: param
  })
  .done(r => {
  audioArray = r.audio;
  console.log("audio data loaded");
  if (word) play(word);
  });
}

function play(word) {
 if (!audioArray) getFileArray(word);
 else {
var foundID = audioArray.lowercase.indexOf(word);
console.log("foundID", foundID);
if (foundID > -1) {
  var audio = new Audio();
  audio.src = 'http://test.diglin.eu/' + audioArray.path + audioArray.files[foundID];
  audio.play();
   }
  }
}

我试图提供的代码param

$.getJSON('json_files/jsonData_' + ID + '.json', function(json) {

 var jsonDataLanguage = json.main_object.language;
}

JSON(具有唯一 ID)的外观如下:

{
"main_object": {
"id": "new",
"getExerciseTitle": "TestToConfirm",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
  "title": "TestToConfirm",
  "language": "nl_NL",
  "exercises": [
    {
      "word": "Hallo Marja.",
      "syllables": [
        "hallo",
        "marja",
        "",
        ""
      ]
    }
  ]
},
"dataType": "json"
}
}

所以接下来的事情应该发生(但当我尝试这样做时不起作用):

我尝试在我的 json 文件中访问所需的 ID。在我的 JSON 文件中,我还发送了一种语言,它应该获取该语言并作为param. 我试过这样做,但它会引发错误:“json is not defined”。很可能是因为我没有访问具有特定 ID 的 JSON 文件。我怎么能这样做?我知道这是问题所在,但我不知道如何解决。

标签: javascriptaudio

解决方案


这是代码,与错误无关的所有内容都已删除。首先,分配按钮单击处理程序,该处理程序获取单词并尝试播放相应的音频。如果尚未加载音频数组,getFileArray则调用该音频,然后在完成回调中播放音频。

如果要做更多工作,建议将done()代码移动到单独的函数中。

编辑:固定请求格式

EDIT2:添加了第二个请求

var audioArray;
var LANGUAGE, WORDS, audioArray;

$(document).ready(function() {
  $(document).on("click", ".audioButton", function() {
    var word = $(this).parent().find('.exerciseWord').html().toLowerCase() + '.mp3';
    play(word);
  });
  getFileArray(); // load on page load
});

function getFileArray(word) {
  $.getJSON('jsonLanguage/language.json').done(response => {
    LANGUAGE = response.main_object.language;
    WORDS = response.main_object.exerciseGetWordInput;
    $.post("https://test.diglin.eu/api/media/fileList", {
        language: LANGUAGE
      })
      .done(r => {
        audioArray = r.audio;
        console.log("audio data loaded");
        if (word) play(word);
      });
  });
}

function play(word) {
  if (!audioArray) getFileArray(word);
  else {
    var foundID = audioArray.lowercase.indexOf(word);
    console.log("foundID", foundID);
    if (foundID > -1) {
      var audio = new Audio();
      audio.src = 'http://test.diglin.eu/' + audioArray.path + audioArray.files[foundID];
      audio.play();
    }
  }
}

推荐阅读