Basic Web Audio API 不播放 mp3 文件?

Juh*_*vda 6 html javascript web-audio-api

我正在尝试通过将示例拼凑在一起来学习在线教程。我觉得这应该是播放mp3文件。我正在使用 Chrome 浏览器,它是最新的。我在控制台上没有收到任何错误。我不确定我需要更改或添加什么才能使其工作。

<script type="text/javascript">

//creating an audio context

window.addEventListener('load',init);

function init()
{

    try
    {
        window.AudioContext = window.AudioContext || window.webkitAudioContext;
        var context=new AudioContext();

    }
    catch(e)
    {
        alert("Your browser doesn't support Web Audio API");
    }

    loadSound();
    playSound();
}

//loading sound into the created audio context

function loadSound()
{
    //set the audio file's URL
    var audioURL='audio files/song.mp3';

    //creating a new request
    var request = new XMLhttpRequest();
    request.open("GET",audioURL,true);
    request.responseType= 'arraybuffer';
    request.onLoad funtion(){

        //take the audio from http request and decode it in an audio buffer

        var audioBuffer = null;

        context.decodeAudioData(request.response, function(buffer){ audioBuffer= buffer;});

    }

    request.send();

}, onError);

//playing the audio file
function playSound(buffer) {
  //creating source node
  var source = audioContext.createBufferSource();
  //passing in file
  source.buffer = audioBuffer;

  //start playing
  source.start(0);
}

</script>

</head>


</html>
Run Code Online (Sandbox Code Playgroud)

Juh*_*vda 4

我把这个问题解决了:)我使用了音频标签和网络音频API。这是代码:

var audio = new Audio();
audio.src = 'audio files/song.mp3';
audio.controls = true;
audio.autoplay = true;
document.body.appendChild(audio);

var context = new webkitAudioContext();
var analyser = context.createAnalyser();


window.addEventListener('load', function(e) {
  // Our <audio> element will be the audio source.
  var source = context.createMediaElementSource(audio);
  source.connect(analyser);
  analyser.connect(context.destination);


}, false);
Run Code Online (Sandbox Code Playgroud)

感谢您尝试提供帮助:))