javascript - 读取本地声音文件并在html5 canvas中获取波形

标签 javascript html 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();
}

最佳答案

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

关于javascript - 读取本地声音文件并在html5 canvas中获取波形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28420190/

相关文章:

javascript - 追加 <select> 元素列表

javascript - jsPDF addHTML 将低质量图像导出为 PDF

html - 隐藏子菜单

javascript - 如何在点击时更改按钮图标?

objective-c - 检测新的视频和音频输入

javascript - 有 angularjs 的 slim 框架问题,即 404?

JavaScript 无法在空白窗口中运行

html - Wget 从 html 复制文本

android - 媒体播放器的问题

javascript - 记录器 : Buffer is always empty