2012-11-04 107 views
1

我有一個應用程序,應該從SD卡加載聲音,然後通過單擊按鈕來播放它。當我按一下按鈕我得到logcat的那些消息:無法創建外部文件目錄的Soundpool錯誤裝載/sound1.mp3,樣品0沒有準備好 這是我的代碼:從Sd卡加載聲音的問題

import java.io.File; 

import android.media.AudioManager; 
import android.media.SoundPool; 
import android.os.Bundle; 
import android.app.Activity; 
import android.content.Context; 
import android.view.Menu; 
import android.view.View; 

public class MainActivity extends Activity { 
SoundPool sp; 
int mSoundId; 
int mStreamId = 0; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     sp = new SoundPool(5, AudioManager.STREAM_MUSIC, 0); 
     String path = getFullFilePath(getApplicationContext(), "sound1.mp3"); 
     mSoundId = sp.load(path, 1); 

    } 
    private String getFullFilePath(Context context, String filename) { 
     File directory = context.getExternalFilesDir(null); 
     File file = new File(directory, filename); 
     if (!file.canRead()) { 
      // error handling 
     } 
     return file.getAbsolutePath(); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.activity_main, menu); 
     return true; 
    } 
    public void button1(View view){ 


     if (mStreamId != 0) { 
      sp.stop(mStreamId); 
     } 
     mStreamId = sp.play(mSoundId, 1, 1, 1, 0, 1f); 
    } 
} 

我logcat的錯誤:

11-04 18:56:34.499: D/dalvikvm(6547): GC_EXTERNAL_ALLOC freed 46K, 51% free 2686K/5379K, external 0K/0K, paused 57ms 
11-04 18:56:34.539: W/ApplicationContext(6547): Unable to create external files directory 
11-04 18:58:02.129: E/SoundPool(6644): error loading /sound1.mp3 

添加WRITE_EXTERNAL_STORAGE Premission給出了這樣的錯誤:

11-04 19:58:01.729: E/SoundPool(8022): error loading /mnt/sdcard/Android/data/com.example.idea/files/sound1.mp3 
+1

請發佈您的logcat錯誤,以便我們可以確切地看到發生了什麼。 – Sam

+0

我貼了他們..加入android.permission.WRITE_EXTERNAL_STORAGE給了我另一個錯誤.. – user1798516

+0

你需要'WRITE_EXTERNAL_STORAGE'權限來創建SD卡上的文件夾(或任何東西),有什麼新的錯誤? – Sam

回答

0

有了這個錯誤:

11-04 19:58:01.729: E/SoundPool(8022): error loading /mnt/sdcard/Android/data/com.example.idea/files/sound1.mp3 

你說:

File exists and it is in /mnt/sdcard/ folder. Application should search external storage for sound1.mp3 and load it if it exists.

然而,/mnt/sdcard//mnt/sdcard/Android/data/com.example.idea/files/只需移動sound1.mp3文件到您的應用程序的默認文件夾的SD卡和的Soundpool就能加載它。

+0

我不想那樣做..我想要應用程序在sdcard上的任何位置找到sound1.mp3 .. – user1798516

+0

Android明確建議每個應用程序以有組織的方式存儲其數據[使用這些目錄](http://developer.android.com /guide/topics/data/data-storage.html#filesExternal)。不過你可以用['Environment.getExternalStorageDirectory()'](http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory%28%29)將你的數據整理在sdcard的基礎文件夾中,而不是'context.getExternalFilesDir(空)' – Sam