我确实知道如何解决语言/音频问题,但是我不知道如何将其作为代码组合在一起

时间:2018-06-22 13:32:33

标签: javascript audio

这是我的代码:

$(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”。很可能是因为我没有访问具有特定ID的JSON文件。我该怎么办?我知道这是问题所在,但我不知道如何解决。

1 个答案:

答案 0 :(得分:1)

这是代码,与错误无关的所有内容均已删除。首先,分配按钮单击处理程序,该处理程序将使用单词并尝试播放相应的音频。如果尚未加载音频数组,则会调用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();
    }
  }
}