我想在我的项目中播放资产/文件夹中的随机声音。 这段代码出了什么问题?请帮帮我
这是我的代码:
MediaPlayer player;
AssetFileDescriptor descriptor;
private String[] filelist;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
player = new MediaPlayer();
Button bTutorial1 = (Button) findViewById(R.id.tutorial1);
AssetManager aMan = this.getAssets();
try {
filelist = aMan.list("mysounds/");
// OR
// filelist = aMan.list("/");
} catch (IOException e1) {
e1.printStackTrace();
{
}
bTutorial1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(filelist.length);
try {
String mediaFile = filelist[randomInt];
descriptor = getAssets().openFd(mediaFile);
player.setDataSource(descriptor.getFileDescriptor(),
descriptor.getStartOffset(),
descriptor.getLength());
descriptor.close();
player.prepare();
player.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
点击按钮后没有声音播放。帮我! 没有错误显示。
答案 0 :(得分:0)
试试这个Mediaplayer构造函数:
MediaPlayer player = MediaPlayer.create(Context context, Uri uri);
uri = Uri.parse("file:///android_asset/mysounds/music.mp3");