从 midi 文件创建 url - Javascript

我通过 ajax 请求从服务器发送一个 midi 文件:


// Create new request add token 

const generateRequest = new XMLHttpRequest();

generateRequest.open('POST', '/generate');

generateRequest.setRequestHeader('X-CSRFToken', csrftoken);


generateRequest.onload = () => {

    // Get response from server

    console.log(generateRequest.response);

    // /tmp/music21/tmp5v_ulgkr.mid

    let objectURL = URL.createObjectURL(generateRequest.response);


    document.getElementById('myVisualizer').src = objectURL;

};


// Add the motif to send with the request

const data = new FormData();

data.append('motif', JSON.stringify(notes));


// Send request

generateRequest.send(data);

服务器:


def generate(request):


    if request.method == "POST":


        # Do some stuff

        

        midi = mg.save_melody(melody)


    return HttpResponse(midi, content_type="audio/midi", status=200)

Mi的想法是将mi midi-visualizer的src设置为midi文件:


<midi-visualizer src="" type="staff" id="myVisualizer"></midi-visualizer>

<midi-player sound-font visualizer="#myVisualizer"></midi-player>

但我得到:未捕获类型错误:无法在“URL”上执行“createObjectURL”:未找到与提供的签名匹配的函数。


我也尝试了 srcObject 但没有结果。


如何将 src 更改为我的 midi 文件?


杨魅力
浏览 1626回答 1
1回答

拉丁的传说

我是这样解决的:# Generate the melody based on the seed@require_http_methods(["POST"])def generate(request):&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; # See if method was post&nbsp; &nbsp; if request.method == "POST":&nbsp; &nbsp; &nbsp; &nbsp; # Do some stuff&nbsp; &nbsp; &nbsp; &nbsp; midi = mg.save_melody(melody)&nbsp; &nbsp; &nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; with open(midi, 'rb') as f:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; file_data = f.read()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; response = HttpResponse(file_data, content_type="audio/midi", status=200)&nbsp; &nbsp; &nbsp; &nbsp; except IOError:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; response = JsonResponse({"succes": False}, status=400)&nbsp; &nbsp; &nbsp; &nbsp; return response和 JavaScript:const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;// Create new request add token&nbsp;const generateRequest = new XMLHttpRequest();generateRequest.open('POST', '/generate');generateRequest.setRequestHeader('X-CSRFToken', csrftoken);generateRequest.responseType = 'blob';generateRequest.onload = () => {&nbsp; &nbsp; // Get response from server&nbsp; &nbsp; console.log(generateRequest.response);&nbsp; &nbsp; let objectURL = URL.createObjectURL(generateRequest.response);&nbsp; &nbsp; document.getElementById('myVisualizer').src = objectURL;&nbsp; &nbsp; document.getElementById('playerMidi').src = objectURL;};
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python