2012-11-04 73 views
0

我有使用soundpool播放聲音的按鈕。我想打開我的應用程序,然後手動加載SD卡中的.mp3文件並使用我的按鈕進行播放。 我的Java代碼:如何從SD卡加載和播放聲音

package com.example.idea; 

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

    public class MainActivity extends Activity { 
    SoundPool sp; 
    int mSoundId; 
    int mStreamId; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    mSoundId = sp.load(this, R.raw.sound1, 1); 

} 

    @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);` 
} 
} 

回答

1

因爲你的SD卡通常(但不一定)是外部存儲,我將介紹下面這樣的解決方案。 (如果您的外部存儲指向設備中的內部卡 - 例如在平板電腦上 - ,我的代碼將返回該文件夾的路徑。)

因此,您應該使用另一版本的加載方法SoundPool ,它期望文件路徑(作爲String)而不是資源ID。這是方法文檔的official link。要獲得文件的路徑,你可以用這個方法:

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(); 
} 

在這種情況下,您的相關代碼段是這樣的:

String path = getFullFilePath(getApplicationContext(), "sound1.wav"); 
mSoundId = sp.load(path, 1); 

綜上所述,上面的代碼將搜索用於應用程序外部存儲目錄中的文件。這是訪問非內部存儲文件的標準方式(即,如果外部存儲器是您的SD卡或其他設備,則取決於設備)。


UPDATE

當然,使用外部存儲之前,您應檢查媒體是否可讀(和書面要求的情況下,可寫的)。你可以找到更多關於這個official page的信息。

+0

我要試試這個:)謝謝 – user1798049

+0

String path = getFullFilePath(getApplicationContext(),「sound1.mp3」);使我的應用程序崩潰 – user1798049

+0

什麼是確切的異常消息(logcat)?並且該文件位於該文件夾中,還是位於其他位置? –