Mik*_*yer 3 audio resources android soundpool
我正在尝试从android加载声音.声音在res/raw/myownsound.wav.我知道我已经可以使用以下方式加载声音:
soundPool.load(context, R.raw.myownsound, 1)
Run Code Online (Sandbox Code Playgroud)
出于自定义目的,我想使用以下方法加载它:
soundPool.load("res/raw/myownsound", 1)
Run Code Online (Sandbox Code Playgroud)
...但是我收到以下错误:error loading res/raw/myownsound.我也尝试过以下方法:
soundPool.loadSound("android.resource://upg.GraphismeBase/raw/myownsound", 1)
Run Code Online (Sandbox Code Playgroud)
..但我也得到一个错误: error loading android.resource://upg.GraphismeBase/raw/myownsound
使用soundPool.load(路径,优先级)的正确方法是什么?
在项目中创建文件夹结构
/assets/sounds/data/
Run Code Online (Sandbox Code Playgroud)
然后在那里复制你的wav文件.
// Declare globally if needed
int mySoundId;
SoundPool soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0 );
AssetManager am = this.getAssets();
//Use in whatever method is used to load the sounds
try {
mySoundId = soundPool.load(am.openFd("sounds/data/myownsound"), 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
可以试试这个(不确定它的工作原理):
SoundPool mySoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
int myAudioFile = getResId("claps", R.raw.class);
try{
mySoundPool.load(context.getActivity(),myAudioFile,1);
} catch (Exception e){
message = String.valueOf(e);
}
public static int getResId(String variableName, Class<?> c) {
Field field = null;
int resId = 0;
try {
field = c.getField(variableName);
try {
resId = field.getInt(null);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return resId;
}
Run Code Online (Sandbox Code Playgroud)
使用名为的上下文这样做的简单工作方式mContext.它通过在运行时获取标识符id按名称加载资源.
int sound_id = mContext.getResources().getIdentifier("myownsound", "raw",
mContext.getPackageName());
soundPool.load(mContext, sound_id, 1);
Run Code Online (Sandbox Code Playgroud)
它也可以加载绘项目或XML文件,通过更换"raw"由"drawable"或"xml"为例子.