需求分析
使用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;
using UnityEngine;
using System.Collections;
using 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;
}
return curAudioSource;
}
} public void OnGUI()
{
if (GUI.Button(new Rect(, , , ), "Stop"))
{
if (CurAudioSource != null) CurAudioSource.Stop();
}
if (GUI.Button(new Rect(, , , ), "Play-MP3"))
{
string audioPath = "/storage/emulated/0/music/千里之外.mp3"; PlayLocalFile(audioPath);
} if (GUI.Button(new Rect(, , , ), "Play-OGG"))
{
string audioPath = "/storage/emulated/0/music/爱上你万岁.ogg";
PlayLocalFile(audioPath);
} if (GUI.Button(new Rect(, , , ), "Play-wav"))
{
string audioPath = "/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}", filePath);
WWW www = new WWW(filePath);
yield return www; if (string.IsNullOrEmpty(www.error))
{
AudioClip audioClip = null;
//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}", www.error);
}
}
}
代码文件: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, true, AudioType.OGGVORBIS); 还是得到一样的错误提示。
IOS平台
ios平台上使用此段代码,会报:unsupported URL
猜测是由于ios上对中文路径的敏感所致。