2017-08-13 34 views
2

我正在使用RecordRTC在我的JavaScript客戶端錄製一些音頻數據。我想通過WebSockets將此音頻數據發送到我的Spring RestController如何將音頻Blob從JavaScript發送到java彈簧服務器?

記錄後,我在我的JavaScript客戶端有一個Blob對象:Blob {size: 65859, type: "audio/webm"}

我想這個BLOB轉換爲使用FileReader一個ArrayBuffer對象,看起來像這樣ArrayBuffer {} byteLength: 65859

我的JavaScript代碼,我發送ArrayBuffer看起來是這樣的:

const reader = new FileReader(); 
    reader.addEventListener('loadend',() => { 
     console.log('readerResult', reader.result); 
     this.stompClient.send("/app/hello", {}, reader.result); 
    }); 

    this.recorder.stopRecording(() => { 
     const blob = this.recorder.getBlob(); 
     reader.readAsArrayBuffer(blob); 
     console.log("blob", blob); 
    }); 

在我的春節,啓動應用程序的WebSocket我的終點是這樣的:

@MessageMapping("/hello") 
public void stream(byte[] input) throws Exception { 
    System.out.println("incoming message ..."); 
    System.out.println(input); 
    System.out.println(input.length); 
} 

這是控制檯輸出:

incoming message ... 
[[email protected] 
20 

在我的服務器的ByteArray只包含20個字節,它看起來像只有元數據被轉移?

如何將記錄的Blob傳輸到我的Spring服務器並創建它的(webm)文件?我是否必須更改我的端點的參數?

+0

你在哪裏調用'.readAsArrayBuffer()'? – guest271314

+0

@ guest271314當我從記錄器中獲取blob時,在我的stopRecording()方法中。我在我的文章中加入了片段 –

+0

'System.out.println(input)'的預期結果是什麼? – guest271314

回答

2

我會建議你使用下面的代碼創建的base64字符串爲您的音頻斑點:

var reader = new FileReader(); 
var base64data; 
reader.readAsDataURL(blob); 
reader.onloadend = function() { 
     base64data = reader.result;     
     console.log(base64data); 
    } 

你會得到的base64字符串是這樣的:

data:audio/webm;base64,T2dnUwACAAAAAAAAAAAyzN3N.... 

現在,在你的後臺更改流的方法代碼爲:

@MessageMapping("/hello") 
public void stream(String base64Audio) throws Exception { 
     System.out.println("incoming message ..."); 
     Decoder decoder = Base64.getDecoder(); 
     byte[] decodedByte = decoder.decode(base64Audio.split(",")[1]); 
     FileOutputStream fos = new FileOutputStream("MyAudio.webm"); 
     fos.write(decodedByte); 
     fos.close(); 
} 
+0

它的工作。非常感謝。我打算髮送音頻塊作爲二進制文件,但我只是意識到base64字符串只是略大於blob。 –

相關問題