Random sound onClick - What's wrong?

All your problems with Audio, Video and Images.

Random sound onClick - What's wrong?

Postby dawidurus » Sat May 18, 2013 9:58 am

Hello!

I'm newbie android's developer.
I've got a problem with my simply app. I want to play random sound from assets folder in my project after click on button. I've made a code, but it doesn't working. I don't know why, no errors in LogCat.


Check it and please help me:

Code: Select all
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("/assets");

        // 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;
}
:roll:
dawidurus
Freshman
Freshman
 
Posts: 2
Joined: Sat May 18, 2013 9:51 am

Top

Return to Multimedia Problems

Who is online

Users browsing this forum: No registered users and 18 guests