使用html5拖放上传后播放mp3文件

inv*_*bob 7 javascript api audio mozilla google-chrome

是否可以首先使用html5拖放上传系统上传mp3文件,然后使用webkit的音频API(http://chromium.googlecode.com/svn/trunk/samples/audio/index.html)进行播放提交表单(在谷歌浏览器中)?是否可以使用Mozilla的音频API在FF中进行?如果是这样,怎么样?另外,webkit的API是否存在任何教程?我找不到任何东西.

Joh*_*Kim 18

您需要遵循的基本流程是

  1. 使用拖放文件捕获文件
  2. 表单数据对象中发布文件
  3. 回复您要播放的音频项目的URL
  4. 使用音频API播放音频

jsFiddle允许您将音频文件拖动到某个区域,然后它将播放该文件.

您应该能够使用JavaScriptAudioNode的onaudioprocess事件来获取当前幅度.

编辑:

根据JaapH的说法,我再次对此进行了研究.处理器用于获取适当的事件来渲染画布.所以它并不是真的需要.这个jsFiddle的作用如下.但是,它使用requestAnimationFrame而不是处理器.

这是旧代码,使用请求动画框架查看上面的小提琴:

var context = new (window.AudioContext || window.webkitAudioContext)();
var source;
var processor;
var analyser;
var xhr;

function initAudio(data) {
    source = context.createBufferSource();

    if(context.decodeAudioData) {
        context.decodeAudioData(data, function(buffer) {
            source.buffer = buffer;
            createAudio();
        }, function(e) {
            console.log(e);
        });
    } else {
        source.buffer = context.createBuffer(data, false /*mixToMono*/);
        createAudio();
    }
}

function createAudio() {
    processor = context.createJavaScriptNode(2048 /*bufferSize*/, 1 /*num inputs*/, 1 /*numoutputs*/);
    processor.onaudioprocess = processAudio;
    analyser = context.createAnalyser();

    source.connect(context.destination);
    source.connect(analyser);

    analyser.connect(processor);
    processor.connect(context.destination);

    source.noteOn(0);
    setTimeout(disconnect, source.buffer.duration * 1000);
}

function disconnect() {
    source.noteOff(0);
    source.disconnect(0);
    processor.disconnect(0);
    analyser.disconnect(0);
}

function processAudio(e) {
    var freqByteData = new Uint8Array(analyser.frequencyBinCount);
    analyser.getByteFrequencyData(freqByteData);
    console.log(freqByteData);
}

function handleResult() {
    if (xhr.readyState == 4 /* complete */) {
        switch(xhr.status) {
            case 200: /* Success */
                initAudio(request.response);
                break;
            default:
                break;
        }
        xhr = null;
    }      
}

function dropEvent(evt) {
    evt.stopPropagation();
    evt.preventDefault();

    var droppedFiles = evt.dataTransfer.files;

    //Ajax the file to the server and respond with the data

    var formData = new FormData();
    for(var i = 0; i < droppedFiles.length; ++i) {
            var file = droppedFiles[i];

            files.append(file.name, file);
    }

    xhr = new XMLHttpRequest();
    xhr.open("POST", 'URL');  
    xhr.onreadystatechange = handleResult;
    xhr.send(formData);
}

function dragOver(evt) {
    evt.stopPropagation();
    evt.preventDefault();
    return false;
}

var dropArea = document.getElementById('dropArea');
dropArea.addEventListener('drop', dropEvent, false);
dropArea.addEventListener('dragover', dragOver, false);
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助