Unity3D PC平台本身是支持直接用www读取本地ogg,wav的,但是并不能读取byte[],字节数组格式,这对用习惯了bass,fmod的人来说有点不方便。

搜了一圈发现了一个C#的音频库叫NAudio,开源并且免费。

https://archive.codeplex.com/?p=naudio

https://github.com/naudio/NAudio

简单粗暴的搞一份二进制release,然后nuget一下ogg扩展

Install-Package NAudio.Vorbis  

使用方面参考了下面3个地址

https://blog.csdn.net/qq992817263/article/details/54647741

https://gamedev.stackexchange.com/questions/114885/how-do-i-play-mp3-files-in-unity-standalone

https://stackoverflow.com/questions/24624939/using-vorbis-and-naudio-to-play-ogg-files

简单来说新建一个NAudioPlayer.cs文件,内容如下

using UnityEngine;
using System.IO;
using System;
using NAudio;
using NAudio.Wave;

public static class NAudioPlayer
{
    static NVorbis.VorbisReader vorbis;
    public static AudioClip FromOggData(byte[] data)
    {
        // Load the data into a stream
        MemoryStream oggstream = new MemoryStream(data);

        vorbis = new NVorbis.VorbisReader(oggstream, false);

        int samplecount = (int)(vorbis.SampleRate * vorbis.TotalTime.TotalSeconds);

        //  AudioClip audioClip = AudioClip.Create("clip", samplecount, vorbis.Channels, vorbis.SampleRate, false, true, OnAudioRead, OnAudioSetPosition);
        AudioClip audioClip = AudioClip.Create("ogg clip", samplecount, vorbis.Channels, vorbis.SampleRate, false, OnAudioRead);
        // Return the clip
        return audioClip;
    }
    static void OnAudioRead(float[] data)
    {
        var f = new float[data.Length];
        vorbis.ReadSamples(f, , data.Length);
        ; i < data.Length; i++)
        {
            data[i] = f[i];
        }
    }
    static void OnAudioSetPosition(int newPosition)
    {
        vorbis.DecodedTime = new TimeSpan(newPosition); //Only used to rewind the stream, we won't be seeking
    }
    public static AudioClip FromWavData(byte[] data)
    {
        WAV wav = new WAV(data);
        AudioClip audioClip = AudioClip.Create(, wav.Frequency, false);
        audioClip.SetData(wav.LeftChannel, );
        return audioClip;
    }
    public static AudioClip FromMp3Data(byte[] data)
    {
        // Load the data into a stream
        MemoryStream mp3stream = new MemoryStream(data);
        // Convert the data in the stream to WAV format
        Mp3FileReader mp3audio = new Mp3FileReader(mp3stream);
        WaveStream waveStream = WaveFormatConversionStream.CreatePcmStream(mp3audio);
        // Convert to WAV data
        WAV wav = new WAV(AudioMemStream(waveStream).ToArray());
        Debug.Log(wav);
        AudioClip audioClip = AudioClip.Create(, wav.Frequency, false);
        audioClip.SetData(wav.LeftChannel, );
        // Return the clip
        return audioClip;
    }

    private static MemoryStream AudioMemStream(WaveStream waveStream)
    {
        MemoryStream outputStream = new MemoryStream();
        using (WaveFileWriter waveFileWriter = new WaveFileWriter(outputStream, waveStream.WaveFormat))
        {
            byte[] bytes = new byte[waveStream.Length];
            waveStream.Position = ;
            waveStream.Read(bytes, , Convert.ToInt32(waveStream.Length));
            waveFileWriter.Write(bytes, , bytes.Length);
            waveFileWriter.Flush();
        }
        return outputStream;
    }
}

/* From http://answers.unity3d.com/questions/737002/wav-byte-to-audioclip.html */
public class WAV
{

    // convert two bytes to one float in the range -1 to 1
    static float bytesToFloat(byte firstByte, byte secondByte)
    {
        // convert two bytes to one short (little endian)
        ) | firstByte);
        // convert to range from -1 to (just below) 1
        return s / 32768.0F;
    }

    )
    {
        ;
        ; i < ; i++)
        {
            value |= (();
        }
        return value;
    }
    // properties
    public float[] LeftChannel { get; internal set; }
    public float[] RightChannel { get; internal set; }
    public int ChannelCount { get; internal set; }
    public int SampleCount { get; internal set; }
    public int Frequency { get; internal set; }

    public WAV(byte[] wav)
    {

        // Determine if mono or stereo
        ChannelCount = wav[];     // Forget byte 23 as 99.999% of WAVs are 1 or 2 channels

        // Get the frequency
        Frequency = bytesToInt(wav, );

        // Get past all the other sub chunks to get to the data subchunk:
        ;   // First Subchunk ID from 12 to 16

        // Keep iterating until we find the data chunk (i.e. 64 61 74 61 ...... (i.e. 100 97 116 97 in decimal))
         && wav[pos + ] ==  && wav[pos + ] ==  && wav[pos + ] == ))
        {
            pos += ;
            ] *  + wav[pos + ] *  + wav[pos + ] * ;
            pos +=  + chunkSize;
        }
        pos += ;

        // Pos is now positioned to start of actual sound data.
        SampleCount = (wav.Length - pos) / ;     // 2 bytes per sample (16 bit sound mono)
        ) SampleCount /= ;        // 4 bytes per sample (16 bit stereo)

        // Allocate memory (right will be null if only mono sound)
        LeftChannel = new float[SampleCount];
        ) RightChannel = new float[SampleCount];
        else RightChannel = null;

        // Write to double array/s:
        ;
         : );
        // while (pos < wav.Length)
        while ((i < SampleCount) && (pos < maxInput))
        {
            LeftChannel[i] = bytesToFloat(wav[pos], wav[pos + ]);
            pos += ;
            )
            {
                RightChannel[i] = bytesToFloat(wav[pos], wav[pos + ]);
                pos += ;
            }
            i++;
        }
    }

    public override string ToString()
    {
        return string.Format("[WAV: LeftChannel={0}, RightChannel={1}, ChannelCount={2}, SampleCount={3}, Frequency={4}]", LeftChannel,
    RightChannel, ChannelCount, SampleCount, Frequency);
    }
}

再挂个AudioSource,简单粗暴读取文件,解码变为byte[]填充进AudioClip,播放即可

void PlayOGG()
{
    string path = Application.dataPath + "/../Audio/Music/a.ogg";
    byte[] data = File.ReadAllBytes(path);
    audioSource.clip = NAudioPlayer.FromOggData(data);
    audioSource.Play();
}
void PlayMP3()
{
    string path = Application.dataPath + "/../Audio/Music/a.mp3";
    byte[] data = File.ReadAllBytes(path);
    audioSource.clip = NAudioPlayer.FromMp3Data(data);
    audioSource.Play();
}
void PlayWAV()
{
    string path = Application.dataPath + "/../Audio/Music/a.wav";
    byte[] data = File.ReadAllBytes(path);
    audioSource.clip = NAudioPlayer.FromWavData(data);
    audioSource.Play();
}

PC平台在Unity3D中播放硬盘ogg,mp3,wav文件的更多相关文章

  1. Unity3D中播放视频的方法

    播放视频其实和贴图非常相像,因为播放视频用到的 MovieTexture 属于贴图 Texture 的子类.Unity3D 支持的视频格式有很多,但是还是建议使用 ogv 格式的视频,使用其他格式依然 ...

  2. (转)在Unity3D中控制动画播放

    用Unity3D也算是好久了,但是每次做项目总还是能学到新的东西.这次做一个TPS的项目就遇到了这样一个问题,如何同时在上下半身播放不同的动画?解决方法其实是很简单,但由于对于动画资源的了解不足导致问 ...

  3. Unity3D中的shader基础知识

    1.Unity中配备了强大的阴影和材料的语言工具称为ShaderLab,以程式语言来看,它类似于CgFX和Direct3D的效果框架语法,它描述了材质所必须要的一切咨询,而不仅仅局限于平面顶点/像素着 ...

  4. vue中解决chrome浏览器自动播放音频 和MP3语音打包到线上

    一.vue中解决chrome浏览器自动播放音频 需求 有新订单的时候,页面自动语音提示和弹出提示框: 问题 chrome浏览器在18年4月起,就在桌面浏览器全面禁止了音视频的自动播放功能.严格地来说, ...

  5. asp.net 网页中播放 flash 和flv

    需求:在网页中播放powerpoint保存的pps文件和mp4文件 经过查阅:发现网页上直接播放pps文件比较麻烦(office web apps server),所以通过工具,将pps文件转换为sw ...

  6. 如何播放 WAV 文件?

    from http://www.vckbase.com/index.php/wv/434 平时,你在多媒体软件的设计中是怎样处理声音文件的呢?使用Windows 提供的API函数 sndPlaySou ...

  7. [Unity3D][Vuforia][IOS]vuforia在unity3d中添加自己的动态模型,识别自己的图片,添加GUI,播放视频

    使用环境 unity3D 5 pro vuforia 4 ios 8.1(6.1) xcode 6.1(6.2) 1.新建unity3d工程,添加vuforia 4.0的工程包 Hierarchy中 ...

  8. Unity3D系列教程--使用免费工具在Unity3D中开发2D游戏 第一节

    声明:   本博客文章翻译类别的均为个人翻译,版权全部.出处: http://blog.csdn.net/ml3947,个人博客:http://www.wjfxgame.com. 译者说明:这是一个系 ...

  9. Unity3d中使用assetbundle

    1.导出assetbundle: ①单个资源导出成assetbundle: ②多个资源导出成一个assetbundle: 2.读取assetbundle: ①加载到内存: ②解压为具体资源. 1.导出 ...

随机推荐

  1. [SQL]某数据库中查出包含 字段名 的所有表名

    --利用SQL语句来查询字段所在的表 --从某数据库中查出包含 字段名 字段的所有表名 SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE ...

  2. NIOS II With uCOSII

    1.如果使用uCOS,那么Qsys中Nios II核就不能使用外部中断控制器(EIC). 2.遇到很迷惑的问题,运行uCOSII的实例代码,总是在第二个OSTimeDlyHMSM(0, 0, 3, 0 ...

  3. js中的数值转换

    js中有3个函数可以把非数值转换为数值:Number().parseInt().parseFloat().其中Number()可以用于任何数据类型.parseInt()及parseFloat()用于将 ...

  4. WEB请求过程(http解析,浏览器缓存机制,域名解析,cdn分发)

    概述 发起一个http请求的过程就是建立一个socket通信的过程. 我们可以模仿浏览器发起http请求,譬如用httpclient工具包,curl命令等方式. curl "http://w ...

  5. springMVC自定义全局异常

    SpringMVC通过HandlerExceptionResolver处理程序异常,包括Handler映射,数据绑定以及目标方法执行时所发生的异常. SpringMVC中默认是没有加装载Handler ...

  6. MySQL慢查询日志相关的配置和使用。

    MySQL慢查询日志提供了超过指定时间阈值的查询信息,为性能优化提供了主要的参考依据,是一个非常实用的功能,MySQL慢查询日志的开启和配置非常简单,可以指定记录的文件(或者表),超过的时间阈值等就可 ...

  7. mysql创建索引以及对索引的理解

    创建表的时候创建索引   创建索引是指在某个表的一列或多列上建立一个索引,以便提高对表的访问速度.创建索引有3种方式,这3种方式分别是创建表的时候创建索引.在已经存在的表上创建索引和使用ALTER T ...

  8. html2canvas

    最近公司有个需求,实现html 页面元素转为png图像,这边用了html2canvas来实现.,这里记录一下,避免以后忘了~~ 官网链接: http://html2canvas.hertzen.com ...

  9. TCP/UDP 常用端口列表

    计算机之间依照互联网传输层TCP/IP协议不同的协议通信,都有不同的对应端口.所以,利用短信(datagram)的UDP,所采用的端口号码不一定和采用TCP的端口号码一样.以下为两种通信协议的端口列表 ...

  10. Setting up Scatter for Web Applications

    [Setting up Scatter for Web Applications] If you are still using scatter-js please move over to scat ...