Advertisement
Wampire86

Unity Naudio MP3 Import

Nov 30th, 2014
360
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.91 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using NAudio.Wave;
  5.  
  6. public class Mp3Import : MonoBehaviour
  7. {
  8.     AudioFileReader reader;
  9.     ISampleProvider provider;
  10.  
  11.     public AudioClip Import(string path, string clipName = "myClip")
  12.     {
  13.         // set the AudioFileReader and SampleProvider
  14.         reader = new AudioFileReader(path);
  15.         provider = reader;
  16.  
  17.         // Total number of samples
  18.         int samples = (int)(reader.WaveFormat.SampleRate * reader.TotalTime.TotalSeconds);
  19.  
  20.         // Unity is going to use the Read() void to read samples from the SampleProvider
  21.         AudioClip.PCMReaderCallback del = Read;
  22.  
  23.         AudioClip clip = AudioClip.Create(clipName, samples, reader.WaveFormat.Channels, reader.WaveFormat.SampleRate, false, false, del);
  24.         return clip;
  25.     }
  26.  
  27.     void Read(float[] data)
  28.     {
  29.         provider.Read(data, 0, data.Length);
  30.     }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement