在创建新的随机音频文件时,播放随机音频onClick不会重置 - Android

时间:2014-05-09 20:28:19

标签: java android file audio random

这里有一个android编程菜鸟。只是尝试让我的音频停止播放并在每次单击我的imageButton时播放新的随机音频。如果你能帮助查明我的问题,那就太好了。

package com.shamu11.musesoundboard;

import java.util.Random;

//import com.shamu11.firstapp.MainActivity;
//import com.shamu11.firstapp.R;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;

public class MainActivity extends Activity {

ImageButton buttonOne;
private final int NUM_SOUND_FILES = 3;
private int mSndFilesMatt[] = new int[NUM_SOUND_FILES];
private Random rnd = new Random();
MediaPlayer matt;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mSndFilesMatt[0] = R.raw.fury;
    mSndFilesMatt[1] = R.raw.knights_of_cydonia;
    mSndFilesMatt[2] = R.raw.supremacy;

    buttonOne = (ImageButton) findViewById(R.id.imageButton1);
    buttonOne.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            int sndToPlay = rnd.nextInt(NUM_SOUND_FILES);
            matt = MediaPlayer.create(MainActivity.this,     mSndFilesMatt[sndToPlay]);
            matt.seekTo(0);
            matt.start();

        }
    });
}
}

1 个答案:

答案 0 :(得分:0)

试试这个

public void onClick(View v) {
            // TODO Auto-generated method stub
            int sndToPlay = rnd.nextInt(NUM_SOUND_FILES);
            matt.reset();
            matt = MediaPlayer.create(MainActivity.this,mSndFilesMatt[sndToPlay]);
            matt.seekTo(0);
            matt.start();
        }