I have button that plays sound using soundpool. I want to open my application and then manually load .mp3 file from SD card and play it with my button.
My java code :
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);`
}
}
Since your SD card is usually (but necessarily) your external storage, I’ll present such a solution below. (If your external storage points to an internal card in your device — e.g. on a tablet –, my code will return a path to that folder.)
Therefore, you should use another version of the load method of
SoundPool, which expects a file path (as aString) instead of a resource ID. This is the official link to the method’s documentation. To get the path of the file, you can use this method:In this case, your relevant code snippet would look like this:
To sum up, the above code will search for the file in your application’s external storage directory. This is the standard way of accessing a non-internal storage file (i.e. it’s device dependent if the external storage is your SD card or something else).
UPDATE:
Of course, before using the external storage, you should check whether the media is readable (and in case of writing requirements, writable). You can find more information on this official page.