为了账号安全,请及时绑定邮箱和手机立即绑定

从 midi 文件创建 url - Javascript

从 midi 文件创建 url - Javascript

杨魅力 2023-08-22 14:40:17
我通过 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 requestconst data = new FormData();data.append('motif', JSON.stringify(notes));// Send requestgenerateRequest.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 文件?
查看完整描述

1 回答

?
拉丁的传说

TA贡献1789条经验 获得超8个赞

我是这样解决的:


# 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;

};


查看完整回答
反对 回复 2023-08-22
  • 1 回答
  • 0 关注
  • 1625 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信