I’m trying to find a best practice in regards to the audio with my game. I would like to respect the users silent mode but directions are given and I would like to be able to override the silent mode if the user presses the volume buttons up or down instead of going into control center and turning off silent mode.
I created a native iOS plugin to accomplish this task but it causes more crashes across iOS devices then actually working. I welcome any suggestions, best practices that other developers use or tweaks to my code that might fix the crashes.
Steps I took to override:
- Created native Object-C plugin
// AVAudioSessionManager.m
#import <AVFoundation/AVFoundation.h>
void _OverrideSilentMode()
{
NSError *error = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
if(error != nil)
{
NSLog(@"Error setting AVAudioSession category: %@", error);
}
[[AVAudioSession sharedInstance] setActive:YES error:&error];
if(error != nil)
{
NSLog(@"Error activating AVAudioSession: %@", error);
}
}
- Integrated into my Unity Audio Manager script
using System;
using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioManager : MonoBehaviour
{
public static AudioManager instance;
public AudioSource[] soundEffects;
public AudioSource backgroundMusic, levelEndMusic;
public AudioSource[] voiceYahoos;
public AudioSource[] instructions;
// Import the Objective-C method for overriding silent mode
#if UNITY_IOS && !UNITY_EDITOR
[DllImport("__Internal")]
private static extern void _OverrideSilentMode();
#endif
private void Awake()
{
// Ensure only one instance of the AudioManager exists
if (instance != null && instance != this)
{
Destroy(gameObject);
return;
}
instance = this;
DontDestroyOnLoad(gameObject);
// Override silent mode on iOS
#if UNITY_IOS && !UNITY_EDITOR
_OverrideSilentMode();
#endif
if (backgroundMusic != null)
{
backgroundMusic.loop = true;
}
}
public void PausebackgroundMusic()
{
if (backgroundMusic != null)
{
backgroundMusic.Pause();
}
}
public void ResumebackgroundMusic()
{
if (backgroundMusic != null)
{
backgroundMusic.UnPause();
}
}
public void PlaySFX(int soundToPlay)
{
if (soundToPlay < soundEffects.Length && soundEffects[soundToPlay] != null)
{
soundEffects[soundToPlay].Stop();
soundEffects[soundToPlay].Play();
}
}
public void StopSFX(int soundToStop)
{
if (soundToStop < soundEffects.Length && soundEffects[soundToStop] != null)
{
soundEffects[soundToStop].Stop();
}
}
}
- Added Plugin to iOS folder in Plugin under Assets
- In XCode, added -ObjC to Other Linker Flags
Thank you in advance for your help.