使用索引基于数组元素播放声音

时间:2014-09-02 19:45:08

标签: android arrays audio

我对android很新,所以请原谅我的无知或无能。

我实际上是在创建一个应用程序,通过在TextView上使用setText显示随机说法,从数组中获取数据。然后我希望能够匹配,并播放适当的音频。

我认为这是通过找到数组中元素的索引并指定一个值来匹配音频文件来完成的。

希望有道理!感谢。

这是我到目前为止所做的:

public class Sayings extends Activity implements OnClickListener {


MediaPlayer mp;

String[] sayings = {"Saying1", "Saying2", "Saying3", "Saying4", "Saying5"};


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

    Button btnRandom = (Button) findViewById(R.id.random_button);
    Button btnNext = (Button) findViewById(R.id.next_button);
    Button btnBack = (Button) findViewById(R.id.back_button);

    btnRandom.setOnClickListener(this);
    btnNext.setOnClickListener(this);
    btnBack.setOnClickListener(this);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.sayings, menu);
    return true;
}

@Override
public void onClick(View v) {

    int resId = 0;

    switch  (v.getId()) {

    case R.id.random_button:
        RandomSaying();
        resId = R.raw.saying1;
        break;

    case R.id.next_button:
        NextSaying();
        break;

    case R.id.back_button:
    BackSaying();
        break;
    }

    if (mp != null) {

    mp.release();
    }

    mp = MediaPlayer.create(this, resId);
    mp.start();



    }


public void RandomSaying () {
    String randomSaying = (sayings[new Random().nextInt(sayings.length)]);

    TextView sayingsTextView = (TextView) findViewById(R.id.displaySayings);

    sayingsTextView.setText('"' + randomSaying + '"');  

}

1 个答案:

答案 0 :(得分:2)

您应该使用HashMap存储字符串和资源ID之间的对应关系:

HashMap<String, Integer> sayingsResIds = new HashMap<String, Integer>();

//when initializing your array sayings, put the corresponding ids : 
sayingsResId.put("saying1",R.raw.saying1); // do this for all your files
// then get the resource id corresponding to your string , when choosing a random saying: 
resId = sayingsResIds.get(randomSaying);