2015-09-12 19 views
6

サーバーは、オーディオデータをbase64データ文字列として保存します。モバイルウェブクライアントは、データを取り出し、オーディオを再生する。オーディオデータのURI文字列をファイルに変換する

しかし、iOSとAndroidのモバイルChromeでデータの再生ができないという問題が見つかりました(issue)。

クライアント側でデータ文字列を.m4aなどのオーディオファイルに変換し、オーディオsrcをファイルにリンクする方法があるかどうかは疑問でした。

答えて

7

は全体で最高の互換性を持っています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でそれをオーディオ要素に渡すことです。ここでは、コードは(私はLinuxでクローム/ Firefoxでそれをテストし、それが動作します)です:

<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 /> 

私はそれが役に立てば幸い、直接ウェブオーディオAPIを使用して考え出した)

+0

Thx、upvoted。 iOS 8でChromeを動作させました。しかし、ChromeとAndroid 4.4.2のデフォルトブラウザはどちらも動作しません –

関連する問題