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

时间:2015-02-09 21:57:43

标签: javascript html5 audio canvas

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

// 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();
}

1 个答案:

答案 0 :(得分:0)

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