⬆️ ⬇️

Web audio offline in Safari for iOS 6



Playback of cached audio in offline mode in Safari for iOS has long been a real challenge, which was considered an unattainable goal . But with the advent of the web audio API (only in the WebKit engines), it finally became possible, despite the fact that you still have to take a few steps.



The bad news is that you still won't be able to cache mp3 files using the application's cache and simply download them using XmlHttpRequest . Safari for iOS 6 will cache mp3 files, but then silently refuses to play them (very useful!)



Base64 goes to the rescue



Due to the fact that the web audio API provides developers with direct access to the audio buffer , you can change the data format on the fly and send them directly to the web audio API for playback. For example, if you encode an mp3 file into a base64 string, then you can decode it into an ArrayBuffer and convert the raw audio data.

Encoding audio file



You can easily convert mp3 file to base64 string using OpenSSL . If you are running Mac OS X, where it is pre-installed, simply open Terminal.app and enter the following command:



 openssl base64 -in [infile] -out [outfile] 


Replace [infile] with the path to your mp3 file, and [outfile] with the path to save the encoded data.

The command will save the base64-encoded audio file representation. Then you can cache this string using any web storage of your choice (for example, application cache , local storage or webSQL )

')

Base64 in ArrayBuffer



To convert base64 to ArrayBuffer, you need to use your solution. See Daniel Baser's solution for base64- binary.js (Daniele Guerrero). This is a good script that was created specifically for this purpose. It converts the base64 string to a Uint8Array and saves it to an ArrayBuffer.

After that you can simply decode the audio data using honey decodeAudioData() from the web audio API.



 var buff = Base64Binary.decodeArrayBuffer(sound); myAudioContext.decodeAudioData(buff, function(audioData) { myBuffer = audioData; }); 


After transcoding audio data, transfer them to the audio buffer and play the sound:



 mySource = myAudioContext.createBufferSource(); mySource.buffer = myBuffer; mySource.connect(myAudioContext.destination); mySource.noteOn(0); 




Demo and source code



View an online demo and source code with additional examples of using the technique from this article.



Browser support



Presented demos work under Safari 6, Chrome Desktop and Safari under iOS6. Technique, potentially, can work in any browser that supports web audio API, therefore, we hope Chrome Mobile will soon add support for it.

At the moment, W3C is promoting the web audio API as standard .

Source: https://habr.com/ru/post/160465/



All Articles