读取本地声音文件并在html5画布中获取波形

Read in local sound file and get the waveform in html5 canvas

本文关键字:html5 布中 获取 波形 声音 文件 读取      更新时间:2023-09-26

我目前正在尝试从用户提供的声音文件中获取波形。现在,从服务器加载的默认歌曲将正确播放和显示,但当用户选择声音文件时,它将播放声音,而不是波形。

// Create a new instance of an audio object and adjust some of its properties
var audio = new Audio();
audio.src = 'song.mp3';
audio.controls = true;
audio.loop = false;
audio.autoplay = true;
// Establish all variables that your Analyser will use
var source, context, analyser, fbc_array, bars, bar_x, bar_width, bar_height;

function initMp3Player(){
    document.getElementById('audio_box').appendChild(audio);
    context = new webkitAudioContext(); // AudioContext object instance
    analyser = context.createAnalyser(); // AnalyserNode method
    // Re-route audio playback into the processing graph of the AudioContext
    source = context.createMediaElementSource(audio);
    source.connect(analyser);
    analyser.connect(context.destination);
}
function init() {
    canvas = document.getElementById('canvas');
    ctx = canvas.getContext('2d');
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    ctx.fillStyle = "rgb(0,0,0)";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    //add load file ability
    document.getElementById('audio_file').onchange = function(){
        audio = new Audio();
        var files = this.files;
        var file = URL.createObjectURL(files[0]); 
        audio.src = file;
        initMp3Player();
    };
    initMp3Player();
}

我不应该再次调用initMp3Player()。