Lame For Unity Wav转Mp3解决方案

来源:互联网 发布:短信阿里云授权服务 编辑:程序博客网 时间:2024/05/07 22:01

Lame For Unity Wav转Mp3解决方案

项目需求是需要把语音识别录音好的wav文件压缩上传, 搜索网上wav转mp3的方案, 看来看去没有提供为unity的解决方案, 虽然有现成的lame编码库, 但是苦于没有封装好的代码可用, 在unity中要同时适用于ios和安卓的封装好的代码, 搜来搜去都毛一个没有.

伟大的github上也都是只有各自的ios和Android平台的实现代码, 然后我就想弄一个封装好直接能在unity里用的,.

还好github找到了NAudio.Lame库, 是用C#写的封装lame库的, 省去好多工作…本来这个库只是为了NAudio提供一个转换MP3的方案, 不是为了给unity里用的…

由于NAuduio里面用到了windows上的一些dll, 不能直接用于ios和安卓平台上, 只能从中剥离出一些关键代码, 比如读取Wav文件的代码部分. 然后整合起来, 然后那个也不会编译lame库

不过还好从晚上搜到了各自平台编译好的.a和.so文件, 还有Windows平台的dll链接库, mac上的目前还没加上.等以后再加吧.

好了废话不多说了, 直接给大家上结果, 我已经把代码分享到了github上了.

Github地址: https://github.com/3wz/Lame-For-Unity.git

欢迎大家加星收藏, 感谢~

在下面放一个测试的代码:

using UnityEngine;using System.Collections;using UnityEngine.UI;using NAudio.Lame;using NAudio.Wave.WZT;using System.IO;public class Test : MonoBehaviour{    public InputField input;    public Button button;    // Use this for initialization    IEnumerator Start()    {        string testWav = "testWav.wav";        string testMp3 = "testMp3.mp3";        WWW www = new WWW(GetFileStreamingAssetsPath(testWav));        yield return www;        if (string.IsNullOrEmpty(www.error))        {            string saveWavPath = Path.Combine(Application.persistentDataPath, testWav);            File.WriteAllBytes(saveWavPath, www.bytes);            button.onClick.AddListener(() =>            {                string saveMp3Path = Path.Combine(Application.persistentDataPath, testMp3);                var bitRate = string.IsNullOrEmpty(input.text) ? LAMEPreset.ABR_128 : (LAMEPreset)int.Parse(input.text);                WaveToMP3(saveWavPath, saveMp3Path, bitRate);                StartCoroutine(PlayMp3(saveMp3Path));            });        }    }    public virtual string GetFileStreamingAssetsPath(string path)    {        string filePath = null;#if UNITY_EDITOR        filePath = string.Format("file://{0}/StreamingAssets/{1}", Application.dataPath, path);#elif UNITY_ANDROID        filePath = string.Format("jar:file://{0}!/assets/{1}", Application.dataPath, path);#else        filePath = string.Format("file://{0}/Raw/{1}", Application.dataPath, path);#endif        return filePath;    }    public static void WaveToMP3(string waveFileName, string mp3FileName, LAMEPreset bitRate = LAMEPreset.ABR_128)    {        using (var reader = new WaveFileReader(waveFileName))        using (var writer = new LameMP3FileWriter(mp3FileName, reader.WaveFormat, bitRate))            reader.CopyTo(writer);    }    private IEnumerator PlayMp3(string path)    {        if (File.Exists(path))        {            var www = new WWW("file:///" + path);            yield return www;            if (string.IsNullOrEmpty(www.error))            {                var audioSource = GetComponent<AudioSource>();                audioSource.clip = www.audioClip;                audioSource.Play();            }        }    }}
原创粉丝点击