1

I just try to play some sounds in android studio by clicking on pictures (imageViews).

I gave each picture a tag in the xml file:

<ImageView
            android:id="@+id/imageView3"
            android:onClick="playPhrase"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:tag="internet"
            app:srcCompat="@drawable/rouven" />

In the main Activity i have this code but it keeps crashing:

public class MainActivity extends AppCompatActivity {

    public void playPhrase(View view) {
        Button buttonPressed = (Button) view;
        Log.i("Button pressed", buttonPressed.getTag().toString());
        MediaPlayer mediaPlayer = MediaPlayer.create(this, 
                getResources().getIdentifier(buttonPressed.getTag().toString(), 
                "raw", getPackageName()));
        mediaPlayer.start();
    }
}

Can't i call this method like that? How to solve that? Im a beginner :-)

Thanks for your help Carlo

Karl
  • 79
  • 1
  • 7
  • 2
    Regarding, *"In the main Activity i have this code but it keeps crashing..."* -- crashing *how*? Do you see any error messages? Have you reviewed information that you may find in the LogCat? – Hovercraft Full Of Eels Jul 14 '21 at 22:26
  • Poor title. Rewrite to summarize your specific technical issue. – Basil Bourque Jul 14 '21 at 22:36
  • Could not execute method for android:onClick --> must be this, maybe I can not cast an image to a button? – Karl Jul 14 '21 at 22:48
  • It's very difficult to debug a crash without a stack trace. See [Unfortunately MyApp has stopped. How can I solve this?](/q/23353173) for Android-specific advice, and [What is a stack trace, and how can I use it to debug my application errors?](/q/3988788) for advice on what to do once you have the stack trace. If you still need help, edit your question to include the **complete stack trace**, as well as **which line of your code** the stack trace points to. – Ryan M Jul 15 '21 at 07:25

1 Answers1

1

1 put a music file to the /res/raw , such as in.wav, in.mp3 media file (here name it as in)

2 change the code to:

 public void playPhrase(View view) {
    MediaPlayer mediaPlayer = MediaPlayer.create(this,
                R.raw.in);
    mediaPlayer.start();
}
zhangxaochen
  • 32,744
  • 15
  • 77
  • 108