1

Tyring 编写一个随机 .wav 文件以使用列表的数组播放。将有几个按钮,每个按钮将播放来自单独数组的一组不同的随机文件。似乎无法让 MediaPlayer.create 接受文件名,即使 Toast 显示名称。

package com.golf.testwaves;


import java.util.Random;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.media.MediaPlayer;



public class MainActivity extends Activity implements OnClickListener {

    static final String [] badshot =   { "allthat", "happy10", "happy27", "happy4", "inhole1"
            };

    MediaPlayer sayIt;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button a = (Button)findViewById(R.id.button1);
    a.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.main, menu);
    return true;
}


@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

    Random r = new Random();
    String random1 = badshot [r.nextInt(4)];
    Toast.makeText(MainActivity.this,random1,Toast.LENGTH_SHORT).show(); //Verify what .raw file was picked.
    sayIt = MediaPlayer.create(MainActivity.this,R.raw.happy4); // This needs to be where it picks the random .wav file.
    sayIt.start();



}
@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    finish();
}

}

我使用“happy4”来确保代码适用于一个 .wav 文件。但似乎仍然无法弄清楚使用 random1 作为文件名的语法。

提前感谢您的帮助。

4

1 回答 1

0

尝试这个。-

int resId = getResources().getIdentifier(random1, "raw", getPackageName());
sayIt = MediaPlayer.create(MainActivity.this, resId);
于 2013-09-29T01:12:31.377 回答