简体   繁体   English

android:如何在单独的按钮上单击按钮时在android中播放声音

[英]android: how to play sound in android on button click from a separate class

I'am a newbie in java and android and i want to play sound in my app on different button clicks, for this purpose I made a separate class for playing sound but could not make it work.I want to call this class and play sound when user clicks on the button. 我是Java和android的新手,我想通过不同的按钮单击在我的应用程序中播放声音,为此,我制作了一个单独的类来播放声音,但无法使其正常工作。我想调用此类并播放声音当用户单击按钮时。 Can anyone help how to make a separate class for media player and call it from a click of a button. 任何人都可以帮助如何为媒体播放器创建单独的类,然后单击按钮即可调用它。

code of the class where i declare the media player 我声明媒体播放器的类的代码

public class CorrectSound extends Activity implements OnPreparedListener{

  public static void playSound(Context context){
    MediaPlayer mp = MediaPlayer.create(context, R.raw.tiktik);
    mp.setOnPreparedListener(null);
  }

  @Override
  public void onPrepared(MediaPlayer mp) {
      // TODO Auto-generated method stub
      mp.start();
  }
}

this is the button which is in separate activity i want to call this class here. 这是在单独活动中的按钮,我想在这里调用此类。

public void optionAClick (View V){
    Intent i = new Intent(Login.this,profile.class);
    startActivity(i);   
}

Ok, delete all in the playSound function, and put this: 好的,删除playSound函数中的所有内容,并输入以下内容:

public static void playSound(Context context){
    MediaPlayer mp = MediaPlayer.create(context, R.raw.tiktik);
    mp.start();
}

Now, whenever you call your function, it will make a sound. 现在,无论何时调用函数,它都会发出声音。

Make a static function in a class and just call it from any class you want. 在一个类中创建一个静态函数,然后从所需的任何类中调用它。

Example

public class MyApplication extends Application {
    ......
    ......

    public static PlaySound(Context context){   
       MediaPlayer mp = MediaPlayer.create(context, R.raw.notif);
       mp.start();
    }    
}

From some other class 从其他班级

Just use this: 只需使用此:

MyApplication.PlaySound(this);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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