play sound while button is pressed -android

后端 未结 2 1097
南旧
南旧 2021-01-02 22:42

i have this code

package com.tct.soundTouch;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.M         


        
2条回答
  •  伪装坚强ぢ
    2021-01-02 23:10

    public class MainActivity extends AppCompatActivity {
    
        Button button;
        MediaPlayer player;
    
    
        @SuppressLint("ClickableViewAccessibility")
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate( savedInstanceState );
            setContentView( R.layout.activity_main );
    
            button = findViewById( R.id.Click );
    
            button.setOnTouchListener( new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
    
                    if (event.getAction()== MotionEvent.ACTION_DOWN) {
                        player= MediaPlayer.create( MainActivity.this,R.raw.horn );
    
                        player.start();
                    }
                    else if(event.getAction()==MotionEvent.ACTION_UP){
                        player.stop();
                        player.release();
                    }
                    return true;
    
                }
            } );
    
        }
    
    }
    

提交回复
热议问题