1

首先,我昨天开始学习 Android 编程。我正在制作一个字符串,并且在每个选择中我都想播放不同的声音。好的,我有一个,但是在另一个选择中播放相同的声音,因为我不知道该怎么做;也许是具有不同情况的开关?谢谢,现在我有这个代码。`

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();
                }
        }
   }
}
4

2 回答 2

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();

   }
  }
 }
于 2012-11-06T08:13:43.613 回答
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();
            }
        }
}

希望这可以帮助。

于 2012-11-06T08:16:50.477 回答