how to play a sound on click of button

后端 未结 4 1445
梦毁少年i
梦毁少年i 2021-01-15 13:16

i am trying to play sound file on the emulator on click of button but i am getting message \"application play audio has stopped unexpectedly\"

my codes are:

相关标签:
4条回答
  • 2021-01-15 14:01

    Move the creation of the MediaPlayer instance to the onCreate method. This will make your application run:

    // creating instance of media player
    MediaPlayer mp; 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mp = MediaPlayer.create(this, R.raw.ljudman__grenade);
    

    Also, if you're trying to start a new instance of your activity upon the button click I believe this is the correct way to do it:

    startActivity(new Intent(p1.this, p1.class));
    
    0 讨论(0)
  • 2021-01-15 14:04

    Try this:

    Button btn1=(Button)findViewById(R.id.xBtn1);
    
    btn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final MediaPlayer mp1=MediaPlayer.create(getBaseContext(), R.raw.fruit_dance);  
            mp1.start();
        }
    }
    
    0 讨论(0)
  • 2021-01-15 14:13
        //inside toggle button 
        toggleButton = (ToggleButton)findViewById(R.id.sound);
        final MediaPlayer mp = MediaPlayer.create(this, R.raw.theme);
        if(toggleButton.isChecked())
            mp.start();
        toggleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!toggleButton.isChecked()){
                    mp.pause();
                }
                else {
                    mp.start();
                    mp.isLooping();
                }
            }
        });
    
    0 讨论(0)
  • 2021-01-15 14:15

    mp.start() should be before starting a new activity.

          btnSound.setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View v) {
                mp.start();
                startActivity(new Intent(currentActivityName.this, newActivityName.class)); 
    
                }
            }); 
    
    0 讨论(0)
提交回复
热议问题