mirror of
https://github.com/cocos/cocos4.git
synced 2026-11-21 08:02:39 +08:00
support audiofocuschange for android (#10246)
* support audiofocuschange for android
This commit is contained in:
@@ -68,6 +68,7 @@ AudioEngine::ProfileHelper * AudioEngine::sDefaul
|
||||
std::unordered_map<int, AudioEngine::AudioInfo> AudioEngine::sAudioIDInfoMap;
|
||||
AudioEngineImpl * AudioEngine::sAudioEngineImpl = nullptr;
|
||||
|
||||
float AudioEngine::sVolumeFactor = 1.0F;
|
||||
uint32_t AudioEngine::sOnPauseListenerID = 0;
|
||||
uint32_t AudioEngine::sOnResumeListenerID = 0;
|
||||
std::vector<int> AudioEngine::sBreakAudioID;
|
||||
@@ -275,12 +276,25 @@ void AudioEngine::setVolume(int audioID, float volume) {
|
||||
}
|
||||
|
||||
if (it->second.volume != volume) {
|
||||
sAudioEngineImpl->setVolume(audioID, volume);
|
||||
sAudioEngineImpl->setVolume(audioID, volume * sVolumeFactor);
|
||||
it->second.volume = volume;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void AudioEngine::setVolumeFactor(float factor) {
|
||||
if (factor > 1.0F) {
|
||||
factor = 1.0F;
|
||||
}
|
||||
if (factor < 0) {
|
||||
factor = 0.0F;
|
||||
}
|
||||
sVolumeFactor = factor;
|
||||
for (auto &item : sAudioIDInfoMap) {
|
||||
sAudioEngineImpl->setVolume(item.first, item.second.volume * sVolumeFactor);
|
||||
}
|
||||
}
|
||||
|
||||
void AudioEngine::pause(int audioID) {
|
||||
auto it = sAudioIDInfoMap.find(audioID);
|
||||
if (it != sAudioIDInfoMap.end() && it->second.state == AudioState::PLAYING) {
|
||||
|
||||
@@ -151,7 +151,13 @@ public:
|
||||
*/
|
||||
static void setVolume(int audioID, float volume);
|
||||
|
||||
/**
|
||||
/**
|
||||
* sets volume factor for all audio instance
|
||||
* @param factor, Volume factor(range from 0.0 to 1.0).
|
||||
*/
|
||||
static void setVolumeFactor(float factor);
|
||||
|
||||
/**
|
||||
* Gets the volume value of an audio instance.
|
||||
*
|
||||
* @param audioID An audioID returned by the play2d function.
|
||||
@@ -367,8 +373,9 @@ protected:
|
||||
static bool sIsEnabled;
|
||||
|
||||
private:
|
||||
static uint32_t sOnPauseListenerID;
|
||||
static uint32_t sOnResumeListenerID;
|
||||
static float sVolumeFactor;
|
||||
static uint32_t sOnPauseListenerID;
|
||||
static uint32_t sOnResumeListenerID;
|
||||
static std::vector<int> sBreakAudioID;
|
||||
|
||||
static void onEnterBackground(const CustomEvent &);
|
||||
|
||||
@@ -85,6 +85,7 @@ public class CocosActivity extends Activity implements SurfaceHolder.Callback {
|
||||
GlobalObject.setActivity(this);
|
||||
CocosHelper.registerBatteryLevelReceiver(this);
|
||||
CocosHelper.init(this);
|
||||
CocosAudioFocusManager.registerAudioFocusListener(this);
|
||||
CanvasRenderingContext2DImpl.init(this);
|
||||
onLoadNativeLibraries();
|
||||
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
|
||||
@@ -166,6 +167,7 @@ public class CocosActivity extends Activity implements SurfaceHolder.Callback {
|
||||
}
|
||||
super.onDestroy();
|
||||
CocosHelper.unregisterBatteryLevelReceiver(this);
|
||||
CocosAudioFocusManager.unregisterAudioFocusListener(this);
|
||||
CanvasRenderingContext2DImpl.destroy();
|
||||
}
|
||||
|
||||
@@ -185,6 +187,9 @@ public class CocosActivity extends Activity implements SurfaceHolder.Callback {
|
||||
Utils.hideVirtualButton();
|
||||
onResumeNative();
|
||||
Utils.hideVirtualButton();
|
||||
if (CocosAudioFocusManager.isAudioFocusLoss()) {
|
||||
CocosAudioFocusManager.registerAudioFocusListener(this);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -213,6 +218,9 @@ public class CocosActivity extends Activity implements SurfaceHolder.Callback {
|
||||
if (!mDestroyed) {
|
||||
onWindowFocusChangedNative(hasFocus);
|
||||
}
|
||||
if (hasFocus && CocosAudioFocusManager.isAudioFocusLoss()) {
|
||||
CocosAudioFocusManager.registerAudioFocusListener(this);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2018-2022 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
http://www.cocos.com
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated engine source code (the "Software"), a limited,
|
||||
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
|
||||
to use Cocos Creator solely to develop games on your target platforms. You shall
|
||||
not use Cocos Creator software for developing other software or tools that's
|
||||
used for developing games. You are not granted to publish, distribute,
|
||||
sublicense, and/or sell copies of Cocos Creator.
|
||||
|
||||
The software or tools in this License Agreement are licensed, not sold.
|
||||
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
package com.cocos.lib;
|
||||
|
||||
import android.content.Context;
|
||||
import android.media.AudioAttributes;
|
||||
import android.media.AudioFocusRequest;
|
||||
import android.media.AudioManager;
|
||||
import android.os.Build;
|
||||
import android.util.Log;
|
||||
|
||||
class CocosAudioFocusManager {
|
||||
|
||||
private static final String _TAG = "CocosAudioFocusManager";
|
||||
private static boolean isAudioFocusLost = true;
|
||||
|
||||
private final static AudioManager.OnAudioFocusChangeListener sAfChangeListener = focusChange -> {
|
||||
Log.d(_TAG, "onAudioFocusChange: " + focusChange + ", thread: " + Thread.currentThread().getName());
|
||||
|
||||
if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
|
||||
// Permanent loss of audio focus
|
||||
// Pause playback immediately
|
||||
Log.d(_TAG, "Pause music by AUDIOFOCUS_LOSS");
|
||||
isAudioFocusLost = true;
|
||||
CocosHelper.runOnGameThreadAtForeground(() -> nativeSetAudioVolumeFactor(0));
|
||||
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
|
||||
// Pause playback
|
||||
Log.d(_TAG, "Pause music by AUDIOFOCUS_LOSS_TRANSILENT");
|
||||
isAudioFocusLost = true;
|
||||
CocosHelper.runOnGameThreadAtForeground(() -> nativeSetAudioVolumeFactor(0));
|
||||
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
|
||||
// Lower the volume, keep playing
|
||||
Log.d(_TAG, "Lower the volume, keep playing by AUDIOFOCUS_LOSS_TRANSILENT_CAN_DUCK");
|
||||
isAudioFocusLost = false;
|
||||
CocosHelper.runOnGameThreadAtForeground(() -> nativeSetAudioVolumeFactor(0.1f));
|
||||
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
|
||||
// Your app has been granted audio focus again
|
||||
// Raise volume to normal, restart playback if necessary
|
||||
Log.d(_TAG, "Resume music by AUDIOFOCUS_GAIN");
|
||||
isAudioFocusLost = false;
|
||||
CocosHelper.runOnGameThreadAtForeground(() -> nativeSetAudioVolumeFactor(1.0f));
|
||||
}
|
||||
};
|
||||
|
||||
static void registerAudioFocusListener(Context context) {
|
||||
AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
|
||||
assert am != null;
|
||||
int result;
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
AudioAttributes playbackAttributes = new AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_GAME)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
|
||||
.build();
|
||||
|
||||
// set the playback attributes for the focus requester
|
||||
AudioFocusRequest focusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK)
|
||||
.setAudioAttributes(playbackAttributes)
|
||||
.setWillPauseWhenDucked(true)
|
||||
.setOnAudioFocusChangeListener(sAfChangeListener)
|
||||
.build();
|
||||
|
||||
result = am.requestAudioFocus(focusRequest);
|
||||
} else {
|
||||
// Request audio focus for playback
|
||||
result = am.requestAudioFocus(sAfChangeListener,
|
||||
// Use the music stream.
|
||||
AudioManager.STREAM_MUSIC,
|
||||
// Request permanent focus.
|
||||
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
|
||||
}
|
||||
|
||||
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
|
||||
Log.d(_TAG, "requestAudioFocus succeed");
|
||||
isAudioFocusLost = false;
|
||||
CocosHelper.runOnGameThreadAtForeground(() -> nativeSetAudioVolumeFactor(1.0f));
|
||||
return;
|
||||
}
|
||||
|
||||
Log.e(_TAG, "requestAudioFocus failed!");
|
||||
}
|
||||
|
||||
static void unregisterAudioFocusListener(Context context) {
|
||||
AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
|
||||
assert am != null;
|
||||
int result = am.abandonAudioFocus(sAfChangeListener);
|
||||
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
|
||||
Log.d(_TAG, "abandonAudioFocus succeed!");
|
||||
} else {
|
||||
Log.e(_TAG, "abandonAudioFocus failed!");
|
||||
}
|
||||
}
|
||||
|
||||
static boolean isAudioFocusLoss() {
|
||||
return isAudioFocusLost;
|
||||
}
|
||||
|
||||
private static native void nativeSetAudioVolumeFactor(float focus);
|
||||
}
|
||||
@@ -33,6 +33,7 @@
|
||||
|
||||
#include <jni.h>
|
||||
#include "JniHelper.h"
|
||||
#include "cocos/audio/include/AudioEngine.h"
|
||||
|
||||
#ifndef JCLS_HELPER
|
||||
#define JCLS_HELPER "com/cocos/lib/CocosHelper"
|
||||
@@ -42,6 +43,11 @@
|
||||
#define JCLS_SENSOR "com/cocos/lib/CocosSensorHandler"
|
||||
#endif
|
||||
|
||||
#ifndef COM_AUDIOFOCUS_CLASS_NAME
|
||||
#define COM_AUDIOFOCUS_CLASS_NAME com_cocos_lib_CocosAudioFocusManager
|
||||
#endif
|
||||
#define JNI_AUDIO(FUNC) JNI_METHOD1(COM_AUDIOFOCUS_CLASS_NAME,FUNC)
|
||||
|
||||
using namespace cc; //NOLINT
|
||||
|
||||
/***********************************************************
|
||||
@@ -145,4 +151,12 @@ void setAccelerometerIntervalJNI(float interval) {
|
||||
|
||||
float *getDeviceMotionValueJNI() {
|
||||
return JniHelper::callStaticFloatArrayMethod(JCLS_SENSOR, "getDeviceMotionValue");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extern "C" {
|
||||
JNIEXPORT void JNICALL JNI_AUDIO(nativeSetAudioVolumeFactor)(JNIEnv* /*env*/, jclass/* thiz*/, jfloat volumeFactor)
|
||||
{
|
||||
AudioEngine::setVolumeFactor(volumeFactor);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user