我怎么停止声音?

时间:2013-06-03 03:33:07

标签: android eclipse

我正在发出警报,以便在关闭项目时如何停止声音????因为当我关闭它时声音仍在播放,如何阻止它?我已经把它放了但是没有用:

@Override
protected void onStop(){
    super.onStop();
    //your code for stopping the sound
}

这是代码

public class MainActivity extends Activity {
    ImageView img;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

          requestWindowFeature(Window.FEATURE_NO_TITLE);
          this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
          WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_main);

           MediaPlayer media = MediaPlayer.create(getBaseContext(), R.raw.alarm);
            media.start();

        img = (ImageView) findViewById(R.id.img);
            img.setImageResource(R.drawable.image1);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

2 个答案:

答案 0 :(得分:0)

我在项目中使用的是:

在主要活动中声明Ringtone的实例

Ringtone ringtone;

开始播放声音:

ringtone = RingtoneManager.getRingtone(this, Uri.parse(ringUri));
ringtone.play();

如果ringUri是uri你要播放的铃声或声音。

停止声音:

ringtone.stop();

答案 1 :(得分:0)

将MediaPlayer媒体变量设为全局变量,当onStop触发时,您可以将其停在那里:

private MediaPlayer media;

@Override
protected void onStop(){
    super.onStop();
    //your code for stopping the sound
    if( media != null && media.isPlaying()) {
        media.stop();
    }
}