安卓:从的OnClick / RES随机播放.MP3 /原始文件 [英] Android: OnClick play random .mp3 from /res/raw file
问题描述
我是相当新的Android应用程序的发展,我试图从/ RES /生文件夹播放随机.MP3。
I am fairly new to Android Application development, and I'm trying to play a random .mp3 from the /res/raw folder.
固定我有这到目前为止,但我碰到一个FileNotFoundException异常来了。
FIXED I have this so far, but I came across a FileNotFoundException.
固定只起首先点击一个随机的声音,之后,这是相同的声音,除非重新打开该应用程序。
FIXED Only plays a random sound on first click, after that it is the same sound unless reopen the app.
新问题立即播放随机的声音,但是当我点击该按钮多次的声音开始在玩耍的同时,仍然在日志中获得开始()穆里为空的消息。
NEW ISSUE Now plays random sounds, but when I click the button multiple times the sounds start playing at the same time and still getting the "start() mUri is null" message in the logs.
修订code
MediaPlayer player;
int soundIndex;
AssetFileDescriptor descriptor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* gets a random index from an array of sounds
*
* @return
*/
public int getRandomSoundIndex(){
int soundIndex;
int[] sound = SOUNDZ;
Random random = new Random();
soundIndex = random.nextInt(sound.length);
return sound[soundIndex];
}
/**
* Plays that random sound on button click
* @param button
*/
public void playRandomSound(View button){
//where button is physically located
button = (Button) findViewById(R.id.button1);
//get random sound index
soundIndex = getRandomSoundIndex();
//make media player
player = MediaPlayer.create(this, soundIndex);
//play sound
player.start();
}
下面是日志:
17 09-21:42:32.528:D / MediaPlayer的(4282):开始()穆里为空
09-21 17:42:32.528: D/MediaPlayer(4282): start() mUri is null
推荐答案
在这里你有一些问题。
首先,调用的toString()
在字段
会给你一个串重的presentation对象实例,如公共静态最终诠释com.lena.button.R $ raw.laptopkeyboard1
,这是不是非常有用的。 presumably,你希望调用getInt()
。
First, calling toString()
on a Field
will give you a string representation of the object instance, such as "public static final int com.lena.button.R$raw.laptopkeyboard1"
, which is not very useful. Presumably, you want getInt()
.
二,原料资源不是资产,所以你不使用 openFd()
。相反,使用静态创建()
方法来创建你的的MediaPlayer
实例,传递 INT
你获得调用getInt()
在字段
。
Second, a raw resource is not an asset, and so you do not use openFd()
. Instead, use the static create()
method to create your MediaPlayer
instance, passing in the int
you get from getInt()
on your Field
.
第三,反射是缓慢的。请不要做一次以上。使用 R.raw.class.getFields()
的一次的,缓存的结果。或者,更好的,考虑不使用反射可言,而是使用自己的文字的Java INT []
:
Third, reflection is slow. Please do not do it more than once. Use R.raw.class.getFields()
once, caching the results. Or, better yet, consider not using reflection at all, and instead using your own literal Java int[]
:
static int[] SOUNDZ={R.raw.boom, R.raw.chaka, R.raw.laka};
(在你自己的声音资源替代,当然)
(substituting in your own sound resources, of course)
这篇关于安卓:从的OnClick / RES随机播放.MP3 /原始文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!