AudioKit 音频播放相关的功能如下:
对应的 API 调用方式如下:
btnPlayGame.onClick.AddListener(() => { AudioKit.PlayMusic("resources://game_bg"); });
btnPlaySound.onClick.AddListener(() => { AudioKit.PlaySound("resources://game_bg"); });
btnPlayVoiceA.onClick.AddListener(() => { AudioKit.PlayVoice("resources://game_bg"); });
AudioKit 设置相关的功能如下:
调用示例如下:
btnSoundOn.onClick.AddListener(() => { AudioKit.Settings.IsSoundOn.Value = true; });
btnSoundOff.onClick.AddListener(() => { AudioKit.Settings.IsSoundOn.Value = false; });
btnMusicOn.onClick.AddListener(() => { AudioKit.Settings.IsMusicOn.Value = true; });
btnMusicOff.onClick.AddListener(() => { AudioKit.Settings.IsMusicOn.Value = false; });
btnVoiceOn.onClick.AddListener(() => { AudioKit.Settings.IsVoiceOn.Value = true; });
btnVoiceOff.onClick.AddListener(() => { AudioKit.Settings.IsVoiceOn.Value = false; });
这是打开声音这个功能的使用方式。
调整音量大小的代码如下:
AudioKit.Settings.MusicVolume.RegisterWithInitValue(v => musicVolumeSlider.value = v);
AudioKit.Settings.VoiceVolume.RegisterWithInitValue(v => voiceVolumeSlider.value = v);
AudioKit.Settings.SoundVolume.RegisterWithInitValue(v => soundVolumeSlider.value = v);
musicVolumeSlider.onValueChanged.AddListener(v => { AudioKit.Settings.MusicVolume.Value = v; });
voiceVolumeSlider.onValueChanged.AddListener(v => { AudioKit.Settings.VoiceVolume.Value = v; });
soundVolumeSlider.onValueChanged.AddListener(v => { AudioKit.Settings.SoundVolume.Value = v; });
与 UIKit 一样, AudioKit 也支持了自定义音频加载的方式。
参考代码如下:
using System;
using UnityEngine;
namespace QFramework.Example
{
public class CustomAudioLoaderExample : MonoBehaviour
{
/// <summary>
/// 定义从 Resources 加载音频
/// </summary>
class ResourcesAudioLoaderPool : AbstractAudioLoaderPool
{
protected override IAudioLoader CreateLoader()
{
return new ResourcesAudioLoader();
}
}
class ResourcesAudioLoader : IAudioLoader
{
private AudioClip mClip;
public AudioClip Clip => mClip;
public AudioClip LoadClip(AudioSearchKeys panelSearchKeys)
{
mClip = Resources.Load<AudioClip>(panelSearchKeys.AssetName);
return mClip;
}
public void LoadClipAsync(AudioSearchKeys audioSearchKeys, Action<bool,AudioClip> onLoad)
{
var resourceRequest = Resources.LoadAsync<AudioClip>(audioSearchKeys.AssetName);
resourceRequest.completed += operation =>
{
var clip = resourceRequest.asset as AudioClip;
onLoad(clip, clip);
};
}
public void Unload()
{
Resources.UnloadAsset(mClip);
}
}
void Start()
{
// 启动时需要调用一次
AudioKit.Config.AudioLoaderPool = new ResourcesAudioLoaderPool();
}
}
}
由于 QFramework 中的 AudioKit 默认是通过 ResKit 加载,所以使用自定义加载方式时,请将项目中如下代码注释掉:
public class AudioKitWithResKitInit
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
public static void Init()
{
AudioKit.Config.AudioLoaderPool = new ResKitAudioLoaderPool();
}
}
关于 AudioKit 就介绍到这。