play sound while button is pressed -android

后端 未结 2 1098
南旧
南旧 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 22:56

    This should work (there was something wrong with your switch-cases I think):

    @Override
    public boolean onTouch(View v, MotionEvent event) 
    {   
    
        switch (event.getAction()) 
        {
    
        case MotionEvent.ACTION_DOWN:
        {
            mediaPlayer.setLooping(true);
            mediaPlayer.start();
        }
    
        break;
        case MotionEvent.ACTION_UP:
        {
            mediaPlayer.pause();
        }
        break;
    }
    
    return true;
    }
    
    0 讨论(0)
  • 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;
    
                }
            } );
    
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题