2016-11-21 1 views
0

Я изучаю Android, и мое первое приложение - простой музыкальный инструмент. На данный момент у меня 7 кнопок, и я использую MediaPlayer для каждого из них. Дело в том, что каждая кнопка имеет одинаковую функциональность, и я хочу избежать оператора switch в методе Onclick - это единственное, что я нахожу в Интернете. Кто-то сказал мне называть кнопки с соответствующим mp3-файлом и писать простую функцию «играть», которая соответствовала бы правой клавише/кнопке, но я думаю, что я не делаю это правильно. Кто-нибудь может мне помочь? Вот что у меня есть, и многое apreciated за помощью:Воспроизведение нескольких mp3-файлов в одной инструкции Onclick?

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); 

    //these buttons have the same name as the mp3 key notes file 

    c1= (Button) findViewById(R.id.key1); 
    c1.setOnClickListener(this); 
    d1= (Button) findViewById(R.id.key2); 
    d1.setOnClickListener(this); 
    e1= (Button) findViewById(R.id.key3); 
    e1.setOnClickListener(this); 
    f1= (Button) findViewById(R.id.key4); 
    f1.setOnClickListener(this);   
    g1= (Button) findViewById(R.id.key5); 
    g1.setOnClickListener(this); 
    a1=(Button) findViewById(R.id.key6); 
    a1.setOnClickListener(this); 
    b1=(Button) findViewById(R.id.key7); 
    b1.setOnClickListener(this); 

Метод OnClick (первый, если пример работает, конечно, но если я хочу сложный инструмент, я повторил код Так я. хочу это "другое", чтобы быть единственным заявлением):

@Override 
public void onClick(View v) { 

    Button b = (Button)v; 
    String note=b.getText().toString(); 

    if(v==c1){ 
     mp = MediaPlayer.create(this, R.raw.c1); 
     mp.start(); 
     } 
     else{ 
     play(note+".mp3"); 
     } 

И попытка метода воспроизведения:

public void play(String note){ 
    note.equals("cs2");//?? 

    //the mp3 files are stored in res/raw and I also tried that specific path  but it didnt work. The keys are silent, except the c1 

}   

EDIT: Теперь у меня есть только это:

public void play(String note){ 
     mp = MediaPlayer.create(this,getResources().getIdentifier(note,"raw",getPackageName())); 
     mp.start(); 
    } 

    @Override 
    public void onClick(View v) { 

    clickCount++; 
    updateClickCount(); 

    Button b = (Button)v; 
    String note=b.getText().toString(); 
    play(note); 
    } 

Но приложение по-прежнему падает

EDIT: XML

  <?xml version="1.0" encoding="utf-8"?> 

     <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:id="@+id/activity_main2" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:paddingBottom="@dimen/activity_vertical_margin" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
tools:context="com.example.vtorferreira.sounds.MainActivity"> 



<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/activity_main" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context="com.example.vtorferreira.sounds.MainActivity"> 

    <ImageView 
     android:layout_width="300dp" 
     android:layout_height="1200dp" 
     android:id="@+id/kid" 
     android:src="@drawable/kid" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentRight="true" 
     android:clickable="true"/> 



    <ImageView 
     android:layout_width="300dp" 
     android:layout_height="1200dp" 
     android:id="@+id/partido" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentRight="true" 
     android:clickable="true"/> 


    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:orientation="vertical" 
     android:layout_weight="10"> 

     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_weight="5" 
      android:orientation="horizontal" 
      android:weightSum="34" 
      android:gravity="center"> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="1" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#9BC53D" 
       android:visibility="invisible" 
       android:id="@+id/key1_ext"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="2" 
       android:layout_marginLeft="1dp" 
       android:layout_marginRight="1dp" 
       android:background="#000000" 
       android:visibility="invisible" 
       android:id="@+id/black1"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="1" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#2660A4" 
       android:visibility="invisible" 
       android:id="@+id/key2_ext"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="2" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#000000" 
       android:visibility="invisible" 
       android:id="@+id/black2"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="1" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#399E5A" 
       android:visibility="invisible" 
       android:id="@+id/key3_ext"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="1" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#5F0F40" 
       android:visibility="invisible" 
       android:id="@+id/key4_ext"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="2" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#000000" 
       android:visibility="invisible" 
       android:id="@+id/black3"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="1" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#FA7921" 
       android:visibility="invisible" 
       android:id="@+id/key5_ext"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="2" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#000000" 
       android:visibility="invisible" 
       android:id="@+id/black4"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="1" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#9BC53D" 
       android:visibility="invisible" 
       android:id="@+id/key6_ext"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="2" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#000000" 
       android:visibility="invisible" 
       android:id="@+id/black5"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="1" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#2660A4" 
       android:visibility="invisible" 
       android:id="@+id/key7_ext"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="1" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#399E5A" 
       android:visibility="invisible" 
       android:id="@+id/key8_ext"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="2" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#000000" 
       android:visibility="invisible" 
       android:id="@+id/black6"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="1" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#5F0F40" 
       android:visibility="invisible" 
       android:id="@+id/key9_ext"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="2" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#000000" 
       android:visibility="invisible" 
       android:id="@+id/black7"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="1" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#FA7921" 
       android:visibility="invisible" 
       android:id="@+id/key10_ext"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="2" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#000000" 
       android:visibility="invisible" 
       android:id="@+id/black8"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="1" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#9BC53D" 
       android:visibility="invisible" 
       android:id="@+id/key11_ext"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="1" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#2660A4" 
       android:visibility="invisible" 
       android:id="@+id/key12_ext"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="2" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#000000" 
       android:visibility="invisible" 
       android:id="@+id/black9"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="1" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#399E5A" 
       android:visibility="invisible" 
       android:id="@+id/key13_ext"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="2" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#000000" 
       android:visibility="invisible" 
       android:id="@+id/black10"/> 
      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="1" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#5F0F40" 
       android:visibility="invisible" 
       android:id="@+id/key14_ext"/> 









     </LinearLayout> 

     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_weight="10" 
      android:orientation="horizontal" 
      android:weightSum="7" 
      android:gravity="center"> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="0.5" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#2660A4" 
       android:visibility="invisible" 
       android:id="@+id/key1"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="0.5" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#2660A4" 
       android:visibility="invisible" 
       android:id="@+id/key2"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="0.5" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#399E5A" 
       android:visibility="invisible" 
       android:id="@+id/key3"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="0.5" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#5F0F40" 
       android:visibility="invisible" 
       android:id="@+id/key4"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="0.5" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#FA7921" 
       android:visibility="invisible" 
       android:id="@+id/key5"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="0.5" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#9BC53D" 
       android:visibility="invisible" 
       android:id="@+id/key6"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="0.5" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#2660A4" 
       android:visibility="invisible" 
       android:id="@+id/key7"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="0.5" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#399E5A" 
       android:visibility="invisible" 
       android:id="@+id/key8"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="0.5" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#5F0F40" 
       android:visibility="invisible" 
       android:id="@+id/key9"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="0.5" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#FA7921" 
       android:visibility="invisible" 
       android:id="@+id/key10"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="0.5" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#9BC53D" 
       android:visibility="invisible" 
       android:id="@+id/key11"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="0.5" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#2660A4" 
       android:visibility="invisible" 
       android:id="@+id/key12"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="0.5" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#399E5A" 
       android:visibility="invisible" 
       android:id="@+id/key13"/> 

      <Button 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="0.5" 
       android:layout_marginLeft="3dp" 
       android:layout_marginRight="3dp" 
       android:background="#5F0F40" 
       android:visibility="invisible" 
       android:id="@+id/key14"/> 





     </LinearLayout> 

     <LinearLayout 

      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_weight="6" 
      android:orientation="horizontal" 
      android:weightSum="10" 
      android:gravity="center"> 

      <TextView 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:layout_weight="1" 
       android:gravity="center" 
       android:id="@+id/pontos" 
       android:textSize="15sp" 
       android:textStyle="normal|bold" /> 

     </LinearLayout> 

     <LinearLayout 

      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_weight="0" 
      android:orientation="horizontal" 
      android:weightSum="8" 
      android:gravity="center"> 

      <LinearLayout 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:layout_weight="0" 
       android:orientation="horizontal" 
       android:gravity="center"> 

       <Button 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_weight="1" 
        android:layout_marginLeft="2dp" 
        android:layout_marginRight="2dp" 
        android:background="#2072CA" 
        android:id="@+id/pref" 
        android:text="Preferences" 

        /> 
       <ToggleButton 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_weight="1" 
        android:layout_marginLeft="2dp" 
        android:layout_marginRight="2dp" 
        android:background="#2072CA" 
        android:id="@+id/solo" 
        android:textOff="Play Magic Piano!" 
        android:textOn="Close Piano"/> 

       <Button 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_weight="1" 
        android:layout_marginLeft="2dp" 
        android:layout_marginRight="2dp" 
        android:background="#2072CA" 
        android:id="@+id/learn" 
        android:text="Learn about piano" 
        /> 

      </LinearLayout> 

     </LinearLayout> 


     </LinearLayout> 

    </RelativeLayout> 



    </RelativeLayout> 
+0

Зачем регистрироваться в журнале ошибок? – HelloSadness

+0

он по-прежнему указывает на игру (примечание) на Onclick и на mp = Mediaplayer и т. Д. В способе воспроизведения – FuManchu

+0

, но что такое stacktrace ...? сообщение об ошибке, которое появляется в ваших журналах. – HelloSadness

ответ

0

расширение Удалить файл (+».mp3") и использование:
getResources().getIdentifier("FILE NAME WITHOUT EXTENSION","raw", getPackageName())

Кроме того, убедитесь каждый вашего текста кнопки содержит имя файла, присутствующее в вашей необработанной папке без расширения. Например, «c1».

Вот как должен выглядеть окончательный код:

@Override 
public void onClick(View v) { 
    Button b = (Button)v; 
    String note = b.getText().toString().toLowerCase(); 
    play(note); 
} 

public void play(String note){ 
    try { 
    mp = MediaPlayer.create(this,getResources().getIdentifier(note,"raw", getPackageName())); 
    mp.start(); 
    } catch (Exception e) { 
    Log.e("Error", "error playing file with name : " + note + "\n" + e); 
    } 

} 

Вы должны установить текст на кнопках элементов. Для каждого из них вы должны указать имя файла. например, добавление android:text"c1":

<Button 
    android:text="c1" 
    android:layout_width="0dp" 
    android:layout_height="match_parent" 
    android:layout_weight="0.5" 
    android:layout_marginLeft="3dp" 
    android:layout_marginRight="3dp" 
    android:background="#2660A4" 
    android:visibility="visible" 
    android:id="@+id/key1"/> 

Чтобы прояснить немного, код получить текст на кнопке. например 'c1'. Затем ваше приложение попытается найти файл с именем c1 в вашей исходной папке. Если вы не устанавливаете текст на своих кнопках ... Тогда, конечно, ваше приложение не найдет никакого ресурса с именем «!». Надеюсь, ты понимаешь, что я имею в виду.

+0

Я только что отредактировал свой ответ! – HelloSadness

+0

спасибо за комментарий слово примечание здесь - openRawResource (note)); становится красным подчеркнуто. Он говорит: openRawResource (int) в Ресурсах не может быть применен к (java.lang.String) – FuManchu

+0

yep, только что отредактировал ответ ... мой плохой – HelloSadness