简体   繁体   中英

Playing Audio in Android onTouch

I am writing code to play a sound and vibrate when a user touches the screen and when he lift his finger up the vibration and the sound stops. Help required to play the audio ... everything is working including vibration but the audio is not played... the audio file name is tr.mp3

this is my code:-

package dynamitechetan.trimmersimulator;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final ImageView b = (ImageView) findViewById(R.id.bg1);
    final MediaPlayer mp = new MediaPlayer();
     b.setOnTouchListener(new View.OnTouchListener() {

         public boolean onTouch(View v, MotionEvent event) {
         Vibrator vb = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
             if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN) {
                 vb.vibrate(1000 * 60 * 10);//10mins
                 b.setImageResource(R.drawable.img2);

 //                     mp.seekTo(0);
//
////                    mp.reset(); 
//                     mp.start();
                 try {
                     mp.reset();
                     AssetFileDescriptor afd;
                     afd = getAssets().openFd("tr.mp3");
                     mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                     mp.prepare();
                     mp.start();
                 }  catch (IOException e) {
                     e.printStackTrace();
                 }


                 return true;
             }
             if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP) {
                 vb.cancel();

                     mp.stop();


                 b.setImageResource(R.drawable.img1);
                 return false;
             }
             return false;
         }

     });

}

}

MediaPlayer mp;

Inside Oncreate()

mp= MediaPlayer.create(getApplicationContext(), R.raw.tr);

Music file should be in your raw directory

To start music

mp.start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM