首先,我昨天开始使用Android编程。我正在制作一个弦乐,在每个选择中我想演奏不同的声音。好吧,我有一个,但在其他选择中播放相同的声音,因为我不知道该怎么做;也许是一个具有不同情况的Switch?谢谢 现在我有了这段代码。
import android.app.ListActivity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class sonidos extends ListActivity {
public String[] frases = {
"cake",
"butter",
"apple",
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, frases));
}
public void onListItemClick(ListView parent, View v){
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.sonidos);
}
public void onListItemClick(ListView parent, View v, long id){
MediaPlayer sound = MediaPlayer.create(sonidos.this, R.raw.dtrain);
if (sound.isPlaying()) {
sound.stop();
} else {
try {
sound.start();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}
}
答案 0 :(得分:0)
你需要写这样的东西:
public void onListItemClick(ListView parent, View v, long id){
MediaPlayer sound = null;
switch (id) { // argument 'id' is the row of the clicked item
case FIRST_ROW:
sound = MediaPlayer.create(sonidos.this, R.raw.dtrain);
break;
case SECOND_ROW:
sound = MediaPlayer.create(sonidos.this, R.raw.bell);
break;
// and so on ...
}
if (sound.isPlaying()) {
sound.stop();
} else {
try {
sound.start();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}
答案 1 :(得分:0)
如果您使用assets
文件夹中的声音,可以使用以下内容:
public void onListItemClick(ListView parent, View v, long id){
MediaPlayer player = new MediaPlayer();
AssetFileDescriptor afd;
try {
switch(id)
{
case 1: afd = getAssets().openFd("cake.mp3"); break;
case 2: afd = getAssets().openFd("butter.mp3"); break;
default : afd = getAssets().openFd("apple.mp3"); break;
};
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
player.prepare();
} catch (IOException e) {
e.printStackTrace();
SM.Exception("## Exception playing sound!");
}
if (player.isPlaying()) {
player.stop();
}
else {
try {
player.start();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}
希望这有帮助。