gpt4 book ai didi

android - 静音和取消静音我的 Activity 应用程序的声音

转载 作者:太空宇宙 更新时间:2023-11-03 10:21:13 34 4
gpt4 key购买 nike

我构建了一个应用程序,我只想将这个应用程序的声音静音和取消静音。我发现这段代码可以静音:

    AudioManager aManager=(AudioManager)getSystemService(AUDIO_SERVICE);
aManager.setStreamMute(AudioManager.STREAM_MUSIC, true);

它将设备的所有声音静音并禁用设备设置声音的设置,而不仅仅是应用程序的声音。我发现这段代码可以取消静音:

    AudioManager aManager=(AudioManager)getSystemService(AUDIO_SERVICE);
aManager.setStreamMute(AudioManager.STREAM_MUSIC, false);

当我将声音静音并单击包含此代码的按钮时,此代码未运行并且我的设备的声音设置仍处于禁用状态。我只想静音和取消静音我的应用程序的声音,而不是我的设备。有什么更正吗?

最佳答案

试试这段代码:

import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
Button play, mute, data, max;
private boolean VolIsMute;
AudioManager manager;
int currentVolume;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
VolIsMute = false;
init();
}
public void isMute() {
if (VolIsMute) {
manager.setStreamMute(AudioManager.STREAM_MUSIC, false);
VolIsMute = false;
} else {
manager.setStreamMute(AudioManager.STREAM_MUSIC, true);
VolIsMute = true;
}
}
public void init() {
max = (Button) findViewById(R.id.max);
play = (Button) findViewById(R.id.start);
mute = (Button) findViewById(R.id.mute);
play.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
MediaPlayer mp = MediaPlayer.create(
getApplicationContext(), R.raw.abc);
mp.start();
} catch (NullPointerException e) {
e.printStackTrace();
Log.d("WTF", "error: " + e);
}

}
});
}
public void mute(View view) {
currentVolume = manager.getStreamVolume(AudioManager.STREAM_MUSIC);
if (currentVolume == 0) {
Toast.makeText(getApplicationContext(),
" Volume is " + currentVolume +"Press unmute", Toast.LENGTH_SHORT).show();
} else {
isMute();
}
}
public void checvol(View view) {

currentVolume = manager.getStreamVolume(AudioManager.STREAM_MUSIC);
if (currentVolume != 0) {
Toast.makeText(getApplicationContext(),
"Press unmute", Toast.LENGTH_SHORT).show();
} else {
isMute();
}
}
}

I used two buttons one for mute and other for unmute. Check the current volume first and then do appropriately with if -else.

对于那些简化这个的人,不要忘记发布代码。

关于android - 静音和取消静音我的 Activity 应用程序的声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20943254/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com