Sync with cocos2d-x v3 branch ddb4dc8 commit.

This commit is contained in:
James Chen
2017-04-24 10:49:02 +08:00
parent 91cfd45ee9
commit fc98b4bdc0
115 changed files with 5389 additions and 2620 deletions
@@ -304,6 +304,7 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe
protected void onResume() {
Log.d(TAG, "onResume()");
super.onResume();
Cocos2dxAudioFocusManager.registerAudioFocusListener(this);
this.hideVirtualButton();
resumeIfHasFocus();
}
@@ -329,12 +330,14 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe
protected void onPause() {
Log.d(TAG, "onPause()");
super.onPause();
Cocos2dxAudioFocusManager.unregisterAudioFocusListener(this);
Cocos2dxHelper.onPause();
mGLSurfaceView.onPause();
}
@Override
protected void onDestroy() {
Cocos2dxAudioFocusManager.unregisterAudioFocusListener(this);
super.onDestroy();
}
@@ -0,0 +1,131 @@
/****************************************************************************
* Copyright (c) 2017 Chukong Technologies Inc.
*
* http://www.cocos2d-x.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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 org.cocos2dx.lib;
import android.content.Context;
import android.media.AudioManager;
import android.util.Log;
class Cocos2dxAudioFocusManager {
private final static String TAG = "AudioFocusManager";
// Audio focus values synchronized with which in cocos/platform/android/javaactivity-android.cpp
private final static int AUDIOFOCUS_GAIN = 0;
private final static int AUDIOFOCUS_LOST = 1;
private final static int AUDIOFOCUS_LOST_TRANSIENT = 2;
private final static int AUDIOFOCUS_LOST_TRANSIENT_CAN_DUCK = 3;
private static AudioManager.OnAudioFocusChangeListener sAfChangeListener =
new AudioManager.OnAudioFocusChangeListener() {
public void onAudioFocusChange(int 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");
Cocos2dxHelper.runOnGLThread(new Runnable() {
@Override
public void run() {
nativeOnAudioFocusChange(AUDIOFOCUS_LOST);
Cocos2dxHelper.setAudioFocus(false);
}
});
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
// Pause playback
Log.d(TAG, "Pause music by AUDIOFOCUS_LOSS_TRANSILENT");
Cocos2dxHelper.runOnGLThread(new Runnable() {
@Override
public void run() {
nativeOnAudioFocusChange(AUDIOFOCUS_LOST_TRANSIENT);
Cocos2dxHelper.setAudioFocus(false);
}
});
} 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");
Cocos2dxHelper.runOnGLThread(new Runnable() {
@Override
public void run() {
nativeOnAudioFocusChange(AUDIOFOCUS_LOST_TRANSIENT_CAN_DUCK);
Cocos2dxHelper.setAudioFocus(false);
}
});
} 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");
Cocos2dxHelper.runOnGLThread(new Runnable() {
@Override
public void run() {
nativeOnAudioFocusChange(AUDIOFOCUS_GAIN);
Cocos2dxHelper.setAudioFocus(true);
}
});
}
}
};
static boolean registerAudioFocusListener(Context context) {
AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
// Request audio focus for playback
int result = am.requestAudioFocus(sAfChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
Log.d(TAG, "requestAudioFocus succeed");
return true;
}
Log.e(TAG, "requestAudioFocus failed!");
return false;
}
static void unregisterAudioFocusListener(Context context) {
AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
int result = am.abandonAudioFocus(sAfChangeListener);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
Log.d(TAG, "abandonAudioFocus succeed!");
} else {
Log.e(TAG, "abandonAudioFocus failed!");
}
Cocos2dxHelper.runOnGLThread(new Runnable() {
@Override
public void run() {
Cocos2dxHelper.setAudioFocus(true);
nativeOnAudioFocusChange(AUDIOFOCUS_GAIN);
}
});
}
private static native void nativeOnAudioFocusChange(int focusChange);
}
@@ -1,6 +1,6 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
Copyright (c) 2013-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
@@ -410,6 +410,11 @@ public class Cocos2dxHelper {
Cocos2dxHelper.sCocos2dSound.stopAllEffects();
}
static void setAudioFocus(boolean isAudioFocus) {
sCocos2dMusic.setAudioFocus(isAudioFocus);
sCocos2dSound.setAudioFocus(isAudioFocus);
}
public static void end() {
Cocos2dxHelper.sCocos2dMusic.end();
Cocos2dxHelper.sCocos2dSound.end();
@@ -515,7 +520,7 @@ public class Cocos2dxHelper {
}
}
return false;
return defaultValue;
}
public static int getIntegerForKey(String key, int defaultValue) {
@@ -543,7 +548,7 @@ public class Cocos2dxHelper {
}
}
return 0;
return defaultValue;
}
public static float getFloatForKey(String key, float defaultValue) {
@@ -552,7 +557,7 @@ public class Cocos2dxHelper {
return settings.getFloat(key, defaultValue);
}
catch (Exception ex) {
ex.printStackTrace();;
ex.printStackTrace();
Map allValues = settings.getAll();
Object value = allValues.get(key);
@@ -571,7 +576,7 @@ public class Cocos2dxHelper {
}
}
return 0.0f;
return defaultValue;
}
public static double getDoubleForKey(String key, double defaultValue) {
@@ -595,21 +600,21 @@ public class Cocos2dxHelper {
SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(key, value);
editor.commit();
editor.apply();
}
public static void setIntegerForKey(String key, int value) {
SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt(key, value);
editor.commit();
editor.apply();
}
public static void setFloatForKey(String key, float value) {
SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putFloat(key, value);
editor.commit();
editor.apply();
}
public static void setDoubleForKey(String key, double value) {
@@ -617,21 +622,21 @@ public class Cocos2dxHelper {
SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putFloat(key, (float)value);
editor.commit();
editor.apply();
}
public static void setStringForKey(String key, String value) {
SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
editor.commit();
editor.apply();
}
public static void deleteValueForKey(String key) {
SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.remove(key);
editor.commit();
editor.apply();
}
public static byte[] conversionEncoding(byte[] text, String fromCharset,String newCharset)
@@ -1,6 +1,6 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2013-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
@@ -51,6 +51,7 @@ public class Cocos2dxMusic {
private boolean mPaused; // whether music is paused state.
private boolean mIsLoop = false;
private boolean mManualPaused = false; // whether music is paused manually before the program is switched to the background.
private boolean mIsAudioFocus = true;
private String mCurrentPath;
// ===========================================================
@@ -137,7 +138,7 @@ public class Cocos2dxMusic {
if (this.mBackgroundMediaPlayer != null) {
mBackgroundMediaPlayer.release();
mBackgroundMediaPlayer = createMediaPlayer(mCurrentPath);
/**
* should set the state, if not, the following sequence will be error
* play -> pause -> stop -> resume
@@ -226,7 +227,7 @@ public class Cocos2dxMusic {
}
this.mLeftVolume = this.mRightVolume = volume;
if (this.mBackgroundMediaPlayer != null) {
if (this.mBackgroundMediaPlayer != null && mIsAudioFocus) {
this.mBackgroundMediaPlayer.setVolume(this.mLeftVolume, this.mRightVolume);
}
}
@@ -241,7 +242,7 @@ public class Cocos2dxMusic {
Log.e(TAG, "onEnterBackground, IllegalStateException was triggered!");
}
}
public void onEnterForeground(){
try {
if (!this.mManualPaused) {
@@ -254,7 +255,7 @@ public class Cocos2dxMusic {
Log.e(TAG, "onEnterForeground, IllegalStateException was triggered!");
}
}
private void initData() {
this.mLeftVolume = 0.5f;
this.mRightVolume = 0.5f;
@@ -298,6 +299,16 @@ public class Cocos2dxMusic {
return mediaPlayer;
}
void setAudioFocus(boolean isFocus) {
mIsAudioFocus = isFocus;
if (mBackgroundMediaPlayer != null) {
float lVolume = mIsAudioFocus ? mLeftVolume : 0.0f;
float rVolume = mIsAudioFocus ? mRightVolume : 0.0f;
mBackgroundMediaPlayer.setVolume(lVolume, rVolume);
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
@@ -1,6 +1,6 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2013-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
@@ -52,15 +52,19 @@ public class Cocos2dxSound {
private SoundPool mSoundPool;
private float mLeftVolume;
private float mRightVolume;
private boolean mIsAudioFocus = true;
// sound path and stream ids map
// a file may be played many times at the same time
// so there is an array map to a file path
private final HashMap<String, ArrayList<Integer>> mPathStreamIDsMap = new HashMap<String, ArrayList<Integer>>();
// A lock for mPathStreamIDsMap operation to keep mPathStreamIDsMap being visited in only one thread at a time.
private final Object mLockPathStreamIDsMap = new Object();
private final HashMap<String, Integer> mPathSoundIDMap = new HashMap<String, Integer>();
private ConcurrentHashMap<Integer, SoundInfoForLoadedCompleted> mPlayWhenLoadedEffects =
// Key: SoundID, Value: SoundInfoForLoadedCompleted
private ConcurrentHashMap<Integer, SoundInfoForLoadedCompleted> mPlayWhenLoadedEffects =
new ConcurrentHashMap<Integer, SoundInfoForLoadedCompleted>();
private static final int MAX_SIMULTANEOUS_STREAMS_DEFAULT = 5;
@@ -111,24 +115,26 @@ public class Cocos2dxSound {
}
public void unloadEffect(final String path) {
// stop effects
final ArrayList<Integer> streamIDs = this.mPathStreamIDsMap.get(path);
if (streamIDs != null) {
for (final Integer steamID : streamIDs) {
this.mSoundPool.stop(steamID);
synchronized (mLockPathStreamIDsMap) {
// stop effects
final ArrayList<Integer> streamIDs = this.mPathStreamIDsMap.get(path);
if (streamIDs != null) {
for (final Integer steamID : streamIDs) {
this.mSoundPool.stop(steamID);
}
}
this.mPathStreamIDsMap.remove(path);
}
this.mPathStreamIDsMap.remove(path);
// unload effect
final Integer soundID = this.mPathSoundIDMap.get(path);
if(soundID != null){
if (soundID != null) {
this.mSoundPool.unload(soundID);
this.mPathSoundIDMap.remove(path);
}
}
private static int LOAD_TIME_OUT = 500;
private static final int LOAD_TIME_OUT = 500;
public int playEffect(final String path, final boolean loop, float pitch, float pan, float gain){
Integer soundID = this.mPathSoundIDMap.get(path);
@@ -153,11 +159,11 @@ public class Cocos2dxSound {
synchronized(info) {
try {
info.wait(LOAD_TIME_OUT);
}
catch (Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
}
streamID = info.effectID;
mPlayWhenLoadedEffects.remove(soundID);
}
@@ -168,11 +174,13 @@ public class Cocos2dxSound {
public void stopEffect(final int steamID) {
this.mSoundPool.stop(steamID);
// remove record
for (final String pPath : this.mPathStreamIDsMap.keySet()) {
if (this.mPathStreamIDsMap.get(pPath).contains(steamID)) {
this.mPathStreamIDsMap.get(pPath).remove(this.mPathStreamIDsMap.get(pPath).indexOf(steamID));
break;
synchronized (mLockPathStreamIDsMap) {
// remove record
for (final String pPath : this.mPathStreamIDsMap.keySet()) {
if (this.mPathStreamIDsMap.get(pPath).contains(steamID)) {
this.mPathStreamIDsMap.get(pPath).remove(this.mPathStreamIDsMap.get(pPath).indexOf(steamID));
break;
}
}
}
}
@@ -186,46 +194,51 @@ public class Cocos2dxSound {
}
public void pauseAllEffects() {
if (!this.mPathStreamIDsMap.isEmpty()) {
final Iterator<Entry<String, ArrayList<Integer>>> iter = this.mPathStreamIDsMap.entrySet().iterator();
while (iter.hasNext()) {
final Entry<String, ArrayList<Integer>> entry = iter.next();
for (final int steamID : entry.getValue()) {
this.mSoundPool.pause(steamID);
synchronized (mLockPathStreamIDsMap) {
if (!this.mPathStreamIDsMap.isEmpty()) {
final Iterator<Entry<String, ArrayList<Integer>>> iter = this.mPathStreamIDsMap.entrySet().iterator();
while (iter.hasNext()) {
final Entry<String, ArrayList<Integer>> entry = iter.next();
for (final int steamID : entry.getValue()) {
this.mSoundPool.pause(steamID);
}
}
}
}
}
public void resumeAllEffects() {
// can not only invoke SoundPool.autoResume() here, because
// it only resumes all effects paused by pauseAllEffects()
if (!this.mPathStreamIDsMap.isEmpty()) {
final Iterator<Entry<String, ArrayList<Integer>>> iter = this.mPathStreamIDsMap.entrySet().iterator();
while (iter.hasNext()) {
final Entry<String, ArrayList<Integer>> entry = iter.next();
for (final int steamID : entry.getValue()) {
this.mSoundPool.resume(steamID);
synchronized (mLockPathStreamIDsMap) {
// can not only invoke SoundPool.autoResume() here, because
// it only resumes all effects paused by pauseAllEffects()
if (!this.mPathStreamIDsMap.isEmpty()) {
final Iterator<Entry<String, ArrayList<Integer>>> iter = this.mPathStreamIDsMap.entrySet().iterator();
while (iter.hasNext()) {
final Entry<String, ArrayList<Integer>> entry = iter.next();
for (final int steamID : entry.getValue()) {
this.mSoundPool.resume(steamID);
}
}
}
}
}
@SuppressWarnings("unchecked")
public void stopAllEffects() {
// stop effects
if (!this.mPathStreamIDsMap.isEmpty()) {
final Iterator<?> iter = this.mPathStreamIDsMap.entrySet().iterator();
while (iter.hasNext()) {
final Map.Entry<String, ArrayList<Integer>> entry = (Map.Entry<String, ArrayList<Integer>>) iter.next();
for (final int steamID : entry.getValue()) {
this.mSoundPool.stop(steamID);
synchronized (mLockPathStreamIDsMap) {
// stop effects
if (!this.mPathStreamIDsMap.isEmpty()) {
final Iterator<?> iter = this.mPathStreamIDsMap.entrySet().iterator();
while (iter.hasNext()) {
final Map.Entry<String, ArrayList<Integer>> entry = (Map.Entry<String, ArrayList<Integer>>) iter.next();
for (final int steamID : entry.getValue()) {
this.mSoundPool.stop(steamID);
}
}
}
}
// remove records
this.mPathStreamIDsMap.clear();
// remove records
this.mPathStreamIDsMap.clear();
}
}
public float getEffectsVolume() {
@@ -243,13 +256,22 @@ public class Cocos2dxSound {
this.mLeftVolume = this.mRightVolume = volume;
// change the volume of playing sounds
if (!this.mPathStreamIDsMap.isEmpty()) {
final Iterator<Entry<String, ArrayList<Integer>>> iter = this.mPathStreamIDsMap.entrySet().iterator();
while (iter.hasNext()) {
final Entry<String, ArrayList<Integer>> entry = iter.next();
for (final int steamID : entry.getValue()) {
this.mSoundPool.setVolume(steamID, this.mLeftVolume, this.mRightVolume);
if (!mIsAudioFocus)
return;
setEffectsVolumeInternal(mLeftVolume, mRightVolume);
}
private void setEffectsVolumeInternal(float left, float right) {
synchronized (mLockPathStreamIDsMap) {
// change the volume of playing sounds
if (!this.mPathStreamIDsMap.isEmpty()) {
final Iterator<Entry<String, ArrayList<Integer>>> iter = this.mPathStreamIDsMap.entrySet().iterator();
while (iter.hasNext()) {
final Entry<String, ArrayList<Integer>> entry = iter.next();
for (final int steamID : entry.getValue()) {
this.mSoundPool.setVolume(steamID, left, right);
}
}
}
}
@@ -257,7 +279,9 @@ public class Cocos2dxSound {
public void end() {
this.mSoundPool.release();
this.mPathStreamIDsMap.clear();
synchronized (mLockPathStreamIDsMap) {
this.mPathStreamIDsMap.clear();
}
this.mPathSoundIDMap.clear();
this.mPlayWhenLoadedEffects.clear();
@@ -267,7 +291,7 @@ public class Cocos2dxSound {
this.initData();
}
public int createSoundIDFromAsset(final String path) {
private int createSoundIDFromAsset(final String path) {
int soundID = Cocos2dxSound.INVALID_SOUND_ID;
try {
@@ -294,11 +318,14 @@ public class Cocos2dxSound {
return soundID;
}
private float clamp(float value, float min, float max) {
return Math.max(min, (Math.min(value, max)));
}
private float clamp(float value, float min, float max) {
return Math.max(min, (Math.min(value, max)));
}
private int doPlayEffect(final String path, final int soundId, final boolean loop, float pitch, float pan, float gain) {
// Adds 'synchronized' keyword for doPlayeEffect since it's possible to be invoked in GL thread and main thread.
// In Cocos2dxSound.playEffect, it's in GL thread.
// In onLoadComplete callback, it's in main thread.
private synchronized int doPlayEffect(final String path, final int soundId, final boolean loop, float pitch, float pan, float gain) {
float leftVolume = this.mLeftVolume * gain * (1.0f - this.clamp(pan, 0.0f, 1.0f));
float rightVolume = this.mRightVolume * gain * (1.0f - this.clamp(-pan, 0.0f, 1.0f));
float soundRate = this.clamp(SOUND_RATE * pitch, 0.5f, 2.0f);
@@ -306,13 +333,15 @@ public class Cocos2dxSound {
// play sound
int streamID = this.mSoundPool.play(soundId, this.clamp(leftVolume, 0.0f, 1.0f), this.clamp(rightVolume, 0.0f, 1.0f), Cocos2dxSound.SOUND_PRIORITY, loop ? -1 : 0, soundRate);
// record stream id
ArrayList<Integer> streamIDs = this.mPathStreamIDsMap.get(path);
if (streamIDs == null) {
streamIDs = new ArrayList<Integer>();
this.mPathStreamIDsMap.put(path, streamIDs);
synchronized (mLockPathStreamIDsMap) {
// record stream id
ArrayList<Integer> streamIDs = this.mPathStreamIDsMap.get(path);
if (streamIDs == null) {
streamIDs = new ArrayList<Integer>();
this.mPathStreamIDsMap.put(path, streamIDs);
}
streamIDs.add(streamID);
}
streamIDs.add(streamID);
return streamID;
}
@@ -325,19 +354,27 @@ public class Cocos2dxSound {
this.mSoundPool.autoResume();
}
void setAudioFocus(boolean isFocus) {
mIsAudioFocus = isFocus;
float leftVolume = mIsAudioFocus ? mLeftVolume : 0.0f;
float rightVolume = mIsAudioFocus ? mRightVolume : 0.0f;
setEffectsVolumeInternal(leftVolume, rightVolume);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public class SoundInfoForLoadedCompleted {
public boolean isLoop;
public float pitch;
public float pan;
public float gain;
public String path;
public int effectID;
private class SoundInfoForLoadedCompleted {
boolean isLoop;
float pitch;
float pan;
float gain;
String path;
int effectID;
public SoundInfoForLoadedCompleted(String path, boolean isLoop, float pitch, float pan, float gain) {
SoundInfoForLoadedCompleted(String path, boolean isLoop, float pitch, float pan, float gain) {
this.path = path;
this.isLoop = isLoop;
this.pitch = pitch;
@@ -351,9 +388,11 @@ public class Cocos2dxSound {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
// This callback is in main thread.
if (status == 0)
{
SoundInfoForLoadedCompleted info = mPlayWhenLoadedEffects.get(sampleId);
if (info != null) {
info.effectID = doPlayEffect(info.path, sampleId, info.isLoop, info.pitch, info.pan, info.gain);
synchronized (info) {