[英]Download file for offline use Cordova/PhoneGap build
關於應用程序開發,我是新手。 我為Android和iOS開發了一個簡單的音頻播放器應用,並使用phonegap構建。
該應用程序使用<audio>
html標記加載位於遠程服務器上的mp3文件,如下所示:
<div class="mobileui-music-cover-controls">
<audio ontimeupdate="udpateProgress()" id="player">
<source src="http://www.myserver.com/audiofile.mp3" type="audio/mpeg">
</audio>
<a id="playKnop" href="JavaScript:playMusic()" class="play"><i class="ion-ios-play"></i></a>
<a id="pauseKnop" href="JavaScript:pauseMusic()" class="play"><i class="ion-ios-pause"></i></a>
</div>
顯然,我更改了此示例的scr
。
只要您具有穩定的Internet連接,但有些人遇到連接斷開等情況,它就可以正常工作。我想根據用戶要求使文件脫機。 因此,它必須是可選的(通過單擊按鈕或類似的按鈕)。 應用程序應檢測設備上是否存在該文件,如果存在,則選擇本地文件,而不是遠程文件。
簡而言之,我有2個問題。
我似乎無法弄清楚該如何做,最近幾天我一直在努力,但老實說,我對如何實現這一目標一無所知。 任何幫助將不勝感激。
如您所說,您需要將文件下載到設備上。 由於您使用的是cordova,因此可以使用fileTransfer下載音頻。 這非常簡單(這是官方示例代碼):
// !! Assumes variable fileURL contains a valid URL to a path on the device,
// for example, cdvfile://localhost/persistent/path/to/downloads/
var fileTransfer = new FileTransfer();
var uri = encodeURI("http://some.server.com/download.php");
fileTransfer.download(
uri,
fileURL,
function(entry) {
console.log("download complete: " + entry.toURL());
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("download error code" + error.code);
},
false,
{
headers: {
"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
);
下次您要播放音頻時,需要檢查是否有本地版本。 您可以檢查設備是否存在該文件(有很多方法,例如Cordova檢查url中的文件是否存在 ),或者使用諸如localStorage之類的東西,它基本上是一個簡單的lil數據庫。
// more or less pseudo code!!!
// callback from fileTransfer when your file was downloaded
function downloadSuccess(entry) {
// save it to localStorage
// key: the remote URL, value: the local URL
localStorage.setItem(remoteURL, entry.toURL());
}
...
...
// the check if there is a cached file
var remoteSrc = "http://www.myserver.com/audiofile.mp3";
var localSrc = localStorage.getItem(remoteSrc);
if(localSrc === null) {
// when there is NO cached version, use remote
audioElement.src = remoteSrc;
} else {
// when there IS a cached version, use local
audioElement.src = localSrc;
}
希望對您有所幫助,並為您提供一個如何完成簡單緩存的想法:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.