需求分析
使用Everyplay(2121-1540版本)录屏,在升级SDK之后,遇到个问题,调用安卓原生的mediaplay进行播放音乐,在录屏时无法录制到声音,所以想到的解决办法是在Unity中播放音乐文件。
大概解释:
当在手机上选择一首歌(手机上的其它音乐文件)之后,直接在Unity中进行播放。这里需要注意的是这首音乐的格式,大小,存储位置是未知的。
测试环境
Windows 7 x64
Unity 5.3.6 f1 X64
华为 安卓4.2.2 (未ROOT)
三星NOTE3 安卓4.3(未ROOT)
播放其它目录的音频文件(可以是中文文件名,例:千里之外.mp3)
测试代码
以下代码中的音乐文件路径,在测试时,请换成自己的路径。
- "/storage/emulated/0/music/千里之外.mp3";
- "/storage/emulated/0/music/爱上你万岁.ogg";
- "/storage/emulated/0/music/梁静茹_宁夏.wav";
using System; UnityEngine; System.Collections; System.IO; /// <summary> /// Detail : 使用WWW播放音频文件 Author : qingqing-zhao(569032731@qq.com) CreateTime : #CreateTime# </summary> public class PlayAudioByWWW : MonoBehaviour { private AudioSource curAudioSource; public AudioSource CurAudioSource { get { if (curAudioSource != null) return curAudioSource; curAudioSource = gameObject.GetComponent<AudioSource>(); if (curAudioSource == null) { curAudioSource = gameObject.AddComponent<AudioSource>(); curAudioSource.playOnAwake = false; curAudioSource.maxDistance = 1.1f; } curAudioSource; } } void OnGUI() { if (GUI.Button(new Rect(100,200,1)">150,1)">90),1)">"Stop")) { if (CurAudioSource != ) CurAudioSource.Stop(); } 300,1)">Play-MP3string audioPath = /storage/emulated/0/music/千里之外.mp3; PlayLocalFile(audioPath); } Play-OGG/storage/emulated/0/music/爱上你万岁.ogg; PlayLocalFile(audioPath); } Play-wav/storage/emulated/0/music/梁静茹_宁夏.wav; PlayLocalFile(audioPath); } } void PlayLocalFile(string audioPath) { var exists = File.Exists(audioPath); Debug.LogFormat({0},存在:{1},audioPath,exists); StartCoroutine(LoadAudio(audioPath,(audioClip) => { CurAudioSource.clip = audioClip; CurAudioSource.Play(); })); } IEnumerator LoadAudio(string filePath,Action<AudioClip> loadFinish) { //安卓和PC上的文件路径 filePath = file:///" + filePath; Debug.LogFormat(local audioclip :{0}new WWW(filePath); yield www; if (.IsNullOrEmpty(www.error)) { AudioClip audioClip = ; OGG文件会报:Streaming of 'ogg' on this platform is not supported if (filePath.EndsWith("ogg")) { audioClip = www.GetAudioClip(false,true,AudioType.OGGVORBIS); } else { audioClip = www.audioClip; } loadFinish(audioClip); } else { Debug.LogErrorFormat(www load file error:{0}https://github.com/zhaoqingqing/blog_samplecode/blob/master/technical-research/PlayAudioByWWW.cs我的总结
我们知道使用WWW加载Assetbundle时,是不可以有中文名和中文路径的,但上面使用的方法,为什么中文文件可以正常加载并播放?
上述仅仅是通过WWW加载文件,而加载的文件并非Unity的Assetbundle格式,所以写法上和加载Assetbundle不一样。
存在的问题
通过WWW加载ogg格式的音乐文件时,会报 “Streaming of 'ogg' on this platform is not supported “
至于这个Error的解决,目前我的解决办法是:在选择音乐时,如果是ogg格式文件弹出提示。
我尝试使用过 AudioClip audioClip = www.GetAudioClip(false,AudioType.OGGVORBIS); 还是得到一样的错误提示。
IOS平台
ios平台上使用此段代码,会报:unsupported URL
猜测是由于ios上对中文路径的敏感所致。