使用数组作为文件列表的随机波形文件

时间:2013-09-29 01:06:06

标签: android media-player

使用数组为列表编写随机.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作为文件名的语法。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

试试这个.-

int resId = getResources().getIdentifier(random1, "raw", getPackageName());
sayIt = MediaPlayer.create(MainActivity.this, resId);