2015-09-12 88 views
6

服務器將音頻數據保存爲base64數據字符串。移動網絡客戶端獲取數據並播放音頻。將音頻數據uri字符串轉換爲文件

但是在iOS和Android的移動版Chrome中發現一個問題,即數據uri的音頻無法播放(issue)。

爲了使它工作,我想知道在客戶端是否有方法將數據字符串轉換爲音頻文件(如.m4a)並將音頻src鏈接到文件?

回答

7

想通了,直接使用網絡音頻API已遍佈最好的兼容性iOS和Android移動瀏覽器。

function base64ToArrayBuffer(base64) { 
    var binaryString = window.atob(base64); 
    var len = binaryString.length; 
    var bytes = new Uint8Array(len); 
    for (var i = 0; i < len; i++)  { 
    bytes[i] = binaryString.charCodeAt(i); 
    } 
    return bytes.buffer; 
} 

var base64 = '<data string retrieved from server>'; 
var audioContext = new (window.AudioContext || window.webkitAudioContext)(); 
var source = audioContext.createBufferSource(); 
audioContext.decodeAudioData(base64ToArrayBuffer(base64), function(buffer) { 
    source.buffer = buffer; 
    source.connect(audioContext.destination); 
    source.start(0); 
}); 

它適用於iOS Safari,Chrome和Android默認瀏覽器和Chrome。

5

有一種方法可以做到你想要的東西,它可以在桌面上運行,但我無法保證它可以在移動設備上使用。我們的想法是將dataURI轉換爲ArrayBuffer,從中構建一個Blob,然後用它創建一個ObjectURL,傳遞給音頻元素。下面是代碼(我測試了它在Chrome/Firefox的Linux下和它的作品):

<script> 
    var base64audio = "data:audio/ogg;base64,gibberish"; 

    function dataURItoBlob(dataURI) 
    { 
     // Split the input to get the mime-type and the data itself 
     dataURI = dataURI.split(','); 

     // First part contains data:audio/ogg;base64 from which we only need audio/ogg 
     var type = dataURI[ 0 ].split(':')[ 1 ].split(';')[ 0 ]; 

     // Second part is the data itself and we decode it 
     var byteString = atob(dataURI[ 1 ]); 
     var byteStringLen = byteString.length; 

     // Create ArrayBuffer with the byte string and set the length to it 
     var ab = new ArrayBuffer(byteStringLen); 

     // Create a typed array out of the array buffer representing each character from as a 8-bit unsigned integer 
     var intArray = new Uint8Array(ab); 
     for (var i = 0; i < byteStringLen; i++) 
     { 
      intArray[ i ] = byteString.charCodeAt(i); 
     } 

     return new Blob([ intArray ], {type: type}); 
    } 
    document.addEventListener('DOMContentLoaded', function() 
    { 
     // Construct an URL from the Blob. This URL will remain valid until user closes the tab or you revoke it 
     // Make sure at some point (when you don't need the audio anymore) to do URL.revokeObjectURL() with the constructed URL 
     var objectURL = URL.createObjectURL(dataURItoBlob(base64audio)); 

     // Pass the URL to the audio element and load it 
     var audio = document.getElementById('test'); 
     audio.src = objectURL; 
     audio.load(); 
    }); 
</script> 
... 
<audio id="test" controls /> 

我希望幫助;)

+0

Thx,upvoted。它使iOS 8中的Chrome成爲可能。但是,Android 4.4.2中的Chrome和默認瀏覽器都不起作用 –