ImageButton Soundboard android app

一个人想着一个人 提交于 2020-01-11 07:39:13

问题


I'm just starting out with my first soundboard. Basically this is what I have so far (except I have 40 sounds). Does anyone know a better way to do this? I have to go to an appointment, but I will be back later today to respond. Thank you, anyone who can help.

-------------------------soundboard--------------

package com.soundboard.app;

import android.app.Activity; import android.content.Intent; import android.media.MediaPlayer;

import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageButton;

public class main extends Activity {

MediaPlayer sound1, sound2, sound3;


ImageButton button1, button2, button3;



@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);




    sound1 = MediaPlayer.create(this, R.raw.sound1);

    button1 = (ImageButton) findViewById(R.id.button1);
    button1.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            sound1.start();
        }
    });

    squeak3 = MediaPlayer.create(this, R.raw.squeak3);

    dogsqueak = (ImageButton) findViewById(R.id.dogsqueak);
    dogsqueak.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            squeak3.start();
        }
    });





    sound2 = MediaPlayer.create(this, R.raw.sound2);

    button2 = (ImageButton) findViewById(R.id.button2);
    button2.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            sound2.start();

        }
    });




    sound3 = MediaPlayer.create(this, R.raw.sound3);

    button3= (ImageButton) findViewById(R.id.button3);
    button3.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            sound3.start();

        }
    });

}

}


回答1:


With forty buttons you need to arrange for this to happen in a loop.

Although there are even more clever ways to do this, you can start by building a Map:

Map<Integer, Integer> map = new HashMap<Integer, Integer>>();
map.put(R.id.button1, R.raw.sound1);
map.put(R.id.button2, R.raw.sound2);
   ...

and then iterate:

for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    final MediaPlayer sound = MediaPlayer.create(entry.getValue());
    Button button = (ImageButton) findViewById(entry.getKey());
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sound.start();
        }
    });
}

This will give you a taste of a looping solution. You also need to consider how you manage your MediaPlayer instances.



来源:https://stackoverflow.com/questions/5543361/imagebutton-soundboard-android-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!