0
我想從我的項目中的資產/文件夾播放隨機聲音。 該代碼有什麼問題?請幫助我隨機聲音onclick按鈕android assets
這裏是我的代碼:
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;
}
}
點擊按鈕沒有任何聲音後播放。幫我! 不顯示錯誤。
只是檢查的基礎知識:你確定你的媒體音量開?你有調試,以確保文件列表包含有效的文件名? –
是的。我的資產文件夾中有兩個.mp3文件,我也嘗試製作文件夾/ mysounds並添加到那裏。 – user2393513