簡體   English   中英

如何播放音頻Javascript

[英]How to play audio javascript

我有一個網站可以訪問API,該API可以執行文本到語音轉換,並返回mp3(或其他格式)。 這是發出請求並嘗試播放音頻的代碼:

$.ajax({
    url: 'https://westus.tts.speech.microsoft.com/cognitiveservices/v1',
    type: 'post',
    data: '<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="en-US"><voice  name="Microsoft Server Speech Text to Speech Voice (en-US, JessaRUS)">Hello, world!</voice></speak>',
    headers: {
        'Content-Type': 'application/ssml+xml', 'X-Microsoft-OutputFormat': 'audio-16khz-64kbitrate-mono-mp3', 'User-Agent': 'Chat', 'Authorization': token
    },
    success: function (audio) {
        console.log(audio);
        new Audio(audio).play();
    }
});

該請求返回的是一個包含許多奇怪字符和“ LAME3.99.5”的字符串,我不知道如何播放此mp3。 new Audio(audio).play(); 不起作用,因為我沒有文件名,而是原始文件。

一段時間以前,我使用iframe解決了完全相同的問題。 唯一的區別是,我使用IBM Cloud(之前稱為Bluemix)來運行Node-RED實例,該實例又將IBM Watson用於文本到語音轉換。

這是jQuery代碼:

var audio = $('#audio');

//*** Button actions
$("#btnSpeak").on("click", function(e) {
    e.preventDefault();
    // Remove any existing iframe element
    $("#iframeHost").html("");
    // Set the location of Node-RED flow to use
    var baseURL = "https://texasswedenodered.mybluemix.net/speak";
    // Get text to convert to speech
    var text = $("#text").val();
    // Calculate the URL of speech file to insert into iframe
    var url = baseURL+"?text=" + text;
    // Create iframe element in memory
    var iframe = $('<iframe id="audioframe" src="'+url+'" frameborder="1" width="10px" height="10px" style="display:none;"></iframe>');
        $("#iframeHost").append(iframe);
     });

這是iframe的HTML:

<div id="iframeHost"></div>

在純JS中,您將獲取數據,將其轉換為base64,將其作為<source>添加到您的<audio> ,然后就可以播放它。 例如( http://jsbin.com/xuvemuziko/edit?js,output ):

var url = "https://archive.org/download/testmp3testfile/mpthreetest.mp3";

let createAudioElement = data => {
  // we need an <audio> and a <source> element, because that's how web audio works:
  let audio = new Audio();
  let source = document.createElement('source');

  // we know this is an mp3, so use that
  source.type = "audio/mpeg";
  let base64 = btoa(String.fromCharCode(...new Uint8Array(data)));
  source.src = `data:${source.type};base64,${base64}`;
  audio.appendChild(source);

  // And then we play it.
  audio.play();  
};

let handleMP3response = response => {
  response
    .arrayBuffer()
    .then(createAudioElement);
};

fetch(url)
.then(handleMP3response)
.catch(e => console.error(e));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM