从 MIDI 文件中创建 url - Javascript

Create url out of midi file - 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 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 文件?

我是这样解决的:

# Generate the melody based on the seed

@require_http_methods(["POST"])
def generate(request):
    
    # See if method was post
    if request.method == "POST":

        # Do some stuff

        midi = mg.save_melody(melody)

        try:
            with open(midi, 'rb') as f:
                file_data = f.read()

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

        except IOError:
            response = JsonResponse({"succes": False}, status=400)

        return response

和Javascript:

const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;

// Create new request add token 
const generateRequest = new XMLHttpRequest();
generateRequest.open('POST', '/generate');
generateRequest.setRequestHeader('X-CSRFToken', csrftoken);
generateRequest.responseType = 'blob';

generateRequest.onload = () => {
    // Get response from server
    console.log(generateRequest.response);

    let objectURL = URL.createObjectURL(generateRequest.response);
    document.getElementById('myVisualizer').src = objectURL;
    document.getElementById('playerMidi').src = objectURL;
};