[英]Can Android MediaPlayer play audio in a zipped file?
編輯編碼:
我正在為Android開發一個字典應用程序。 我一直在成功地讓應用程序發出每個單詞的意思。 這是代碼:
btnPronounce.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Log.i(MAIN_TAG,"Start pronounciation ...");
btnPronounce.setEnabled(false);
String currentWord = edWord.getText().toString().toLowerCase();
try {
ZipFile zip = new ZipFile("/sdcard/app_folder/sound/zip_test.zip");
ZipEntry entry = zip.getEntry(currentWord);
if (entry != null) {
InputStream in = zip.getInputStream(entry);
// see Note #3.
File tempFile = File.createTempFile("_AUDIO_", ".wav");
FileOutputStream out = new FileOutputStream(tempFile);
IOUtils.copy(in, out);
// do something with tempFile (like play it)
File f = tempFile;
try {
if (f.exists())
{
Log.i(MAIN_TAG,"Audio file found!");
MediaPlayer mp = new MediaPlayer();
mp.prepare();
mp.setLooping(false);
mp.start();
while (mp.getCurrentPosition() < mp.getDuration());
mp.stop();
mp.release();
Log.i(MAIN_TAG,"Pronounciation finished!");
}
else
{
Log.i(MAIN_TAG,"File doesn't exist!!");
}
}
catch (IOException e)
{
Log.i(MAIN_TAG,e.toString());
}
btnPronounce.setEnabled(true); }
else {
// no such entry in the zip
}
} catch (IOException e) {
// handle your exception cases...
e.printStackTrace();
}
}
});
但問題是一個文件夾中的WAV文件太多,所有這些文件都被Android設備視為音樂文件。 因此,索引此類文件需要很長時間。 此外,索引和用戶瀏覽有時會迫使應用程序崩潰。
因此,我只是想知道以下是否可以通過編程方式完成:
編輯:有沒有其他方法/解決方案,只允許將音頻文件放入一個大文件(圖像,zip或類似...),然后讓MediaPlayer讀取其中的單個文件?
非常感謝你。
您可以使用ZipFile
或ZipInputStream
和java.io
文件操作的組合來從zip讀取必要的數據,創建臨時文件並使用MediaPlayer
播放這些文件。
或者,你可以使用TTS引擎而不是傳遞50萬億字節的APK。
編輯 - 按請求示例:
try {
ZipFile zip = new ZipFile("someZipFile.zip");
ZipEntry entry = zip.getEntry(fileName);
if (entry != null) {
InputStream in = zip.getInputStream(entry);
// see Note #3.
File tempFile = File.createTempFile("_AUDIO_", ".wav");
FileOutputStream out = new FileOutputStream(tempFile);
IOUtils.copy(in, out);
// do something with tempFile (like play it)
} else {
// no such entry in the zip
}
} catch (IOException e) {
// handle your exception cases...
e.printStackTrace();
}
筆記:
我這里沒有包含任何安全的文件處理方法。 隨你(由你決定。
這不是做到這一點 ,只有一個辦法做到這一點。 可能有100種其他方式,其中一些可能更適合您的需要。 我沒有使用ZipInputStream
只是因為涉及到更多的邏輯而我只是為了簡潔。 您必須檢查每個條目以查看它是否是您正在尋找的ZipInputStream
,而ZipFile
允許您只是通過名稱詢問您想要的內容。 我不確定使用其他任何一個會產生什么(如果有的話)性能影響。
絕不是你需要使用臨時文件(或者根本就是文件),但Android的MediaPlayer並不真正喜歡流,所以這可能是最簡單的解決方案。
您應該考慮的另一種方法是在用戶想要收聽發音時下載單個聲音文件。 這應該會減小文件大小,盡管它確實意味着在沒有Internet的情況下你不能聽發音。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.