2014-09-02 44 views
0

我對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 + '"'); 

} 
+0

當你運行該代碼你怎麼獲得? – Turkish 2014-09-02 20:53:27

+0

目前它適用於生成隨機說法。無論TextView中出於測試目的什麼,我只會將它設置爲播放指定的「Saying1」。 – 2014-09-02 21:03:15

回答

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); 
+0

感謝您的回覆。我已經按照你的建議去做了,而且它很好地與聲音相配。我現在唯一的問題是,如果我再次按「隨機」按鈕,它不會生成一個新的隨機。它只會在應用程序重啓時執行此操作。 – 2014-09-05 14:27:16

+1

更新:經過多次擺弄我設法解決它!非常感謝你的幫助! – 2014-09-05 15:30:54