/// <summary> /// 通过索引获取一个声音 /// </summary> /// <param name="index">声音索引,有些常量可以在当前类找到</param> /// <param name="isOffLst">是否是附加音频(附加音频是程序默认使用,不再lst文件中)</param> public static AudioClip Get(int index, bool isOffLst) { if (isOffLst) { index += offLst; } string filename = null; if (IndexToFn.ContainsKey(index)) { filename = IndexToFn [index]; } else { if (index > 20000) { index -= 20000; filename = string.Format("M{0:0}-{1:0}", index / 10, index % 10); } else if (index < 10000) { filename = string.Format("{0:000}-{1:0}", index / 10, index % 10); } } WAV wav = new WAV(Path.Combine(Path.Combine(SDK.RootPath, "Wav"), filename + ".wav")); AudioClip audioClip = AudioClip.Create(filename, wav.SampleCount, 1, wav.Frequency, false); audioClip.SetData(wav.LeftChannel, 0); return(audioClip); }
void datosPosicion(int id) { byte[] son = new byte[0]; string conn = "URI=file:" + Application.dataPath + "/Recursos/BD/dbdata.db"; IDbConnection dbconn; dbconn = (IDbConnection) new SqliteConnection(conn); dbconn.Open(); IDbCommand dbcmd = dbconn.CreateCommand(); string sqlQuery = "Select * from ubicacion where id = " + id; dbcmd.CommandText = sqlQuery; IDataReader reader = dbcmd.ExecuteReader(); while (reader.Read()) { son = (byte[])reader["audio_ubicacion"]; Debug.Log(son.Length); yi = reader.GetInt32(6); yf = reader.GetInt32(7); Debug.Log(yi); } WAV sonido = new WAV(son); AudioClip audioClip = AudioClip.Create("Sonido", sonido.SampleCount, 1, sonido.Frequency, false, false); audioClip.SetData(sonido.LeftChannel, 0); audioUbicacion.clip = audioClip; //audioA.Play(); reader.Close(); reader = null; dbcmd.Dispose(); dbcmd = null; dbconn.Close(); }
public static AudioModel FromMp3DataModel(ref byte[] data) { AudioModel model = null; try { // Load the data into a stream using (MemoryStream mp3stream = new MemoryStream(data)) { // Convert the data in the stream to WAV format using (Mp3FileReader mp3audio = new Mp3FileReader(mp3stream)) { // Load the data into a stream using (WaveStream waveStream = WaveFormatConversionStream.CreatePcmStream(mp3audio)) { // Convert to WAV data using (MemoryStream memoryStream = AudioMemStream(waveStream)) { byte[] conversedData = memoryStream.ToArray(); WAV wav = new WAV(ref conversedData); Debug.Log(wav); model = new AudioModel(); model.name = "temp"; model.lengthSamples = wav.SampleCount; model.channel = 1; model.frequency = wav.Frequency; model.stream = false; model.data = wav.LeftChannel; } } } } } catch (Exception e) { Debug.Log(e.Message); } return(model); }
/// <summary> /// テキストからAudioClipを作成 /// </summary> /// <param name="text"></param> /// <returns></returns> private AudioClip CreateAudio(string text) { // 長いテキストを分割 var wavs = new List <WAV>(); var sb = new StringBuilder(); foreach (var cha in text) { sb.Append(cha); if ((cha != '.' && cha != '。' && cha != '\n') || sb.Length <= SEPARATE_THRESHOLD) { continue; } wavs.Add(new WAV(generateAudio.GenerateBinary(sb.ToString()))); sb.Clear(); } if (sb.Length > 1) { wavs.Add(new WAV(generateAudio.GenerateBinary(sb.ToString()))); } // 分割された文の合成 var result = WAV.Combine(wavs.ToArray()); return(result.CreateAudioClip("Audio")); }
public static AudioClip FromMp3Data(byte[] data) { float time = Time.realtimeSinceStartup; // 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);*/ float[] interleavedData; // Convert to WAV data WAV wav = WAVFromMp3Data(data, out interleavedData); Debug.Log("mp3 time: " + (Time.realtimeSinceStartup - time)); time = Time.realtimeSinceStartup; AudioClip audioClip = AudioClip.Create("testSound", wav.SampleCount, 2, wav.Frequency, false); audioClip.SetData(interleavedData, 0); Debug.Log("mp3 time: " + (Time.realtimeSinceStartup - time)); // Return the clip 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()); // Create the AudioClip (stereo) AudioClip audioClip = AudioClip.Create("testSound", wav.SampleCount, 2, wav.Frequency, false); // Create a data array to combine both channels data into a single array of stereo data float[] combinedChannels = new float[wav.LeftChannel.Length + wav.RightChannel.Length]; int pointer = 0; int lpointer = 0; int rpointer = 0; while (pointer < combinedChannels.Length) { combinedChannels[pointer] = wav.LeftChannel[lpointer]; lpointer++; pointer++; combinedChannels[pointer] = wav.RightChannel[rpointer]; rpointer++; pointer++; } // Set the data array to the AudioClip audioClip.SetData(combinedChannels, 0); // Return the clip return(audioClip); }
IEnumerator Record() { character_pages.initValue(); if (blame.guilt == killerName) { character_pages.appendValue(killerName); //We are setting a male voice to this response request_info.setResponseAudioVoice("Richard"); } //In this conditional we will hit only the page corresponding to the character "Anna", //that will respond "No, I didn't kill that guy" to the "Did you kill that guy" question else { character_pages.appendValue(innocentName); //We are setting a female voice to this response request_info.setResponseAudioVoice("Sarah"); } m_clip = Microphone.Start(Microphone.devices[0], true, 1000, 16000); lastPos = 0; // Create a HoundRequester.VoiceRequest object lph.bt = this; request = requester.start_voice_request(null, request_info, lph); sending = true; stopRecording = false; while (Microphone.IsRecording(Microphone.devices[0])) { yield return(null); } sending = false; hound_result = request.finish(); Debug.Log("stopped!"); //StringWriter txt = new StringWriter(); //JSONStreamWriter h = new JSONStreamWriter(txt); //hound_result.write_as_json(h); //Debug.Log(txt.GetStringBuilder().ToString()); ////play the clip back if (hound_result.getAllResults().Count > 0) { wav = new WAV(System.Convert.FromBase64String(hound_result.getAllResults()[0].getResponseAudioBytes())); audioClip = AudioClip.Create("testSound", wav.SampleCount, 1, wav.Frequency, false, false); audioClip.SetData(wav.LeftChannel, 0); audioSource.clip = audioClip; audioSource.Play(); } else { Debug.Log("NO RESULT - ERROR FROM HOUNDIFY"); } }
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()); AudioClip audioClip; if (wav.ChannelCount == 2) { audioClip = AudioClip.Create("Audio File Name", wav.SampleCount, 2, wav.Frequency, false); audioClip.SetData(wav.StereoChannel, 0); } else { audioClip = AudioClip.Create("Audio File Name", wav.SampleCount, 1, wav.Frequency, false); audioClip.SetData(wav.LeftChannel, 0); } // Now return the clip return(audioClip); }
public override unsafe void Replace(string fileName) { IAudioStream stream = null; if (fileName.EndsWith(".wav")) { stream = WAV.FromFile(fileName); } else { base.Replace(fileName); } if (stream != null) { try { ReplaceRaw(RSTMConverter.Encode(stream, null)); } finally { stream.Dispose(); } } int offset = ((int)(Header->DATAData->Data) - (int)(Header)); if (offset < WorkingUncompressed.Length) { _audioSource = new DataSource(Header->DATAData->Data, WorkingUncompressed.Length - offset); SetSizeInternal(offset); } }
public override void deserialize(string s) { string[] tokens = s.Split('#'); setID(int.Parse(tokens[0])); setStart(float.Parse(tokens[1])); setDuration(float.Parse(tokens[2])); string audioName = tokens[3]; WAV wav = new WAV(audioName); AudioClip audioClip = AudioClip.Create(audioName, wav.SampleCount, 1, wav.Frequency, false); audioClip.SetData(wav.LeftChannel, 0); audioSource.clip = audioClip; Vector3 pos = new Vector3(float.Parse(tokens[4]), float.Parse(tokens[5]), float.Parse(tokens[6])); audioVisualCueGO = new GameObject(); audioVisualCueGO.transform.position = pos; audioVisualCueGO.transform.localRotation = Quaternion.identity; audioVisualCueGO.transform.localScale = new Vector3(0.05f, 0.05f, 0.05f); SpriteRenderer sr = audioVisualCueGO.AddComponent <SpriteRenderer>(); sr.sprite = (Sprite)Resources.Load("Sprites/microphone", typeof(Sprite)); _hasBeenCreated = true; }
public override void build(Form parent, IProgressTracker tracker, string tmpwav, string output, bool looping, int loopStart, int length, bool loopTrim) { FileMap audioData; if (loopStart == -2) { BrstmConverterDialog bcd = new BrstmConverterDialog(); bcd.AudioSource = tmpwav; bcd.ShowDialog(parent); if (bcd.DialogResult != DialogResult.OK) { throw new MusicFileException("Build cancelled."); } audioData = bcd.AudioData; } else { IAudioStream audioStream = WAV.FromFile(tmpwav); audioStream.IsLooping = looping; audioStream.LoopStartSample = loopStart; audioStream.LoopEndSample = length; //if (tracker == null) tracker = new ProgressWindow(parent, Shared.PROGRAM_TITLE, "Encoding, please wait...", false); audioData = RSTMConverter.Encode(audioStream, tracker); audioStream.Dispose(); } FileMapWriter.write(audioData, output, FileMode.Create); audioData.Dispose(); }
public static AudioClip LoadFromMp3(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()); int channels = wav.ChannelCount; AudioClip audioClip = AudioClip.Create("testSound", wav.SampleCount, channels, wav.Frequency, false); switch (channels) { case 1: setMonoAudioData(audioClip, wav); break; case 2: setStereoAudioData(audioClip, wav); break; default: throw new ArgumentException("Channel count not supported: " + channels); } return(audioClip); }
public AudioClip ToAudioClip(AssetProvider assetProvider) { if (assetProvider == null) { throw new ArgumentNullException(nameof(assetProvider)); } if (Path == null) { return(null); } else if (IsExternal) { if (File.Exists(Path)) { byte[] fileBytes = File.ReadAllBytes(Path); return(WAV.LoadAudioClip(fileBytes, 0)); } return(null); } else { return((AudioClip)assetProvider.GetAsset(Path)); } }
public static AudioClip LoadAudioClip(string fileName, string clipName) { try { string path = Path.Combine(Path.GetDirectoryName(Module.ModulePath), fileName); WAV wav = new WAV(path); AudioClip audioClip = AudioClip.Create(clipName, wav.SampleCount, 1, wav.Frequency, false); audioClip.SetData(wav.LeftChannel, 0); #if DEBUG Terminal.Log("Audio clip loaded " + clipName); #endif return(audioClip); } catch (Exception exc) { Terminal.Log(exc.Message + ": " + exc.StackTrace); Module.mod.Logger.LogException(exc); } return(null); }
//colores guardados. private void obtenerDatos1(int id) { Debug.Log("funcion con id " + id); byte[] son = new byte[0]; byte[] imagen_personaje = new byte[0]; string conn = "URI=file:" + Application.dataPath + "/Recursos/BD/dbdata.db"; IDbConnection dbconn; dbconn = (IDbConnection) new SqliteConnection(conn); dbconn.Open(); IDbCommand dbcmd = dbconn.CreateCommand(); string sqlQuery; sqlQuery = "select t2.r_color, t2.g_color, t2.b_color, t3.id_personaje, t4.nombre_ubicacion, t3.audio_personaje, t3.imagen_personaje from detalle_aprendizaje as t1 inner join color as t2 on t2.id = t1.id_color inner join personaje as t3 on t1.id_personaje = t3.id_personaje inner join ubicacion as t4 on t1.id_ubicacion = t4.id where t1.id_detalle_apre = " + id; //"select color.r_color, color.g_color, color.b_color, ubicacion.nombre_ubicacion, tpersonaje.audio_personaje, tpersonaje.imagen_personaje from detalle_aprendizaje as detalle_aprendizaje inner join color on color.id = id_color inner join ubicacion on ubicacion.id = id_ubicacion inner join personaje as tpersonaje on tpersonaje.id_personaje = detalle_aprendizaje.id_personaje where id_detalle_apre = " + id; Debug.Log(sqlQuery); dbcmd.CommandText = sqlQuery; IDataReader reader = dbcmd.ExecuteReader(); while (reader.Read()) { nombre_ubicacion = reader.GetString(4); id_personaje_1 = reader.GetInt32(3); imagen_personaje = (byte[])reader["imagen_personaje"]; son = (byte[])reader["audio_personaje"]; if (nombre_ubicacion == "arriba") { id_boton_superior = id_personaje_1; colorSup.r = reader.GetInt32(0); colorSup.g = reader.GetInt32(1); colorSup.b = reader.GetInt32(2); } else { id_boton_inferior = id_personaje_1; colorInf.r = reader.GetInt32(0); colorInf.g = reader.GetInt32(1); colorInf.b = reader.GetInt32(2); } } WAV sonido = new WAV(son); audio_personaje_1 = AudioClip.Create("personaje_1", sonido.SampleCount, 1, sonido.Frequency, false, false); audio_personaje_1.SetData(sonido.LeftChannel, 0); if (nombre_ubicacion == "arriba") { texturaSuperior.LoadImage(imagen_personaje); } else { texturaInferior.LoadImage(imagen_personaje); } reader.Close(); reader = null; dbcmd.Dispose(); dbcmd = null; dbconn.Close(); nombre_ubicacion = ""; StartCoroutine(playsound()); }
public AudioClip GetSoundClip(int group, int index) { KeyValuePair <int, int> key = new KeyValuePair <int, int>(group, index); AudioClip ret = null; if (m_SoundClipMap != null) { if (m_SoundClipMap.TryGetValue(key, out ret)) { return(ret); } } byte[] buf = GetSoundBuf(group, index); if (buf == null || buf.Length <= 0) { return(null); } WAV wav = new WAV(buf); m_SoundBufMap[key] = null; string name = string.Format("{0:D}:{1:D}", group, index); ret = AudioClip.Create(name, wav.SampleCount, 1, wav.Frequency, false, false); ret.SetData(wav.LeftChannel, 0); if (m_SoundClipMap == null) { m_SoundClipMap = new Dictionary <KeyValuePair <int, int>, AudioClip>(); } m_SoundClipMap[key] = ret; return(ret); }
void sonido() { byte[] son = new byte[0]; string conn = "URI=file:" + Application.dataPath + "/Recursos/BD/sonido_prueba.db"; IDbConnection dbconn; dbconn = (IDbConnection) new SqliteConnection(conn); dbconn.Open(); IDbCommand dbcmd = dbconn.CreateCommand(); string sqlQuery = "Select sonido from sonido where id = 1"; dbcmd.CommandText = sqlQuery; IDataReader reader = dbcmd.ExecuteReader(); while (reader.Read()) { son = (byte[])reader["sonido"]; Debug.Log(son.Length); } WAV sonido = new WAV(son); AudioClip audioClip = AudioClip.Create("testSound", sonido.SampleCount, 1, sonido.Frequency, false, false); audioClip.SetData(sonido.LeftChannel, 0); audioA.clip = audioClip; audioA.Play(); reader.Close(); reader = null; dbcmd.Dispose(); dbcmd = null; dbconn.Close(); }
public override unsafe void Export(string outPath) { if (outPath.EndsWith(".wav")) { WAV.ToFile(CreateStreams()[0], outPath); } else { if (_audioSource != DataSource.Empty) { int size = WorkingUncompressed.Length + _audioSource.Length; using (FileStream stream = new FileStream(outPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)) { stream.SetLength(size); using (FileMap map = FileMap.FromStreamInternal(stream, FileMapProtect.ReadWrite, 0, size)) { VoidPtr addr = map.Address; //Write header Memory.Move(addr, WorkingUncompressed.Address, (uint)WorkingUncompressed.Length); //Set the offset to the audio samples (_dataLocation) RSTMHeader *hdr = (RSTMHeader *)addr; hdr->_header._length = WorkingUncompressed.Length + _audioSource.Length; hdr->DATAData->Set(_audioSource.Length + 0x20); addr += WorkingUncompressed.Length; //Append audio samples to the end Memory.Move(addr, _audioSource.Address, (uint)_audioSource.Length); if (outPath.EndsWith(".bcstm")) { ShowADPCMConversionWarning(); byte[] bcstm_temp = CSTMConverter.FromRSTM(hdr); fixed(byte *ptr = bcstm_temp) { Memory.Move(map.Address, ptr, (uint)bcstm_temp.Length); } } else if (outPath.EndsWith(".bfstm")) { ShowADPCMConversionWarning(); byte[] bfstm_temp = FSTMConverter.FromRSTM(hdr); fixed(byte *ptr = bfstm_temp) { Memory.Move(map.Address, ptr, (uint)bfstm_temp.Length); } } } } } else { base.Export(outPath); } } }
static AudioClip LoadBGM(string path) { string type = Path.GetExtension(path).Replace(".", ""); Debug.Log("[Audio] path=" + path + " | type=" + type); AudioClip myClip = null; UnityWebRequest www = null; byte[] byteArray; try { switch (type.ToLower()) { case "ogg": #if UNITY_STANDALONE || UNITY_EDITOR www = UnityWebRequestMultimedia.GetAudioClip(path, AudioType.OGGVORBIS); www.SendWebRequest(); while (!www.isDone) { } myClip = DownloadHandlerAudioClip.GetContent(www); #else byteArray = File.ReadAllBytes(path); myClip = WAV.FromOggData(byteArray); #endif break; case "mp3": #if UNITY_STANDALONE || UNITY_EDITOR byteArray = File.ReadAllBytes(path); myClip = NAudioPlayer.FromMp3Data(byteArray); #else www = UnityWebRequestMultimedia.GetAudioClip("file://" + path, AudioType.MPEG); www.SendWebRequest(); while (!www.isDone) { } myClip = DownloadHandlerAudioClip.GetContent(www); #endif break; case "wav": byteArray = File.ReadAllBytes(path); myClip = WAV.FromWavData(byteArray); break; default: Debug.LogError("Unexpected audio type"); return(null); } Debug.Log("[Audio] Audio Length: " + myClip.length); return(myClip); } catch (System.Exception e) { Debug.LogError("[Audio]錯誤!" + e); return(null); } }
//将wav字节数组转为AudioClip public static AudioClip FromWavData(byte[] data) { WAV wav = new WAV(data); AudioClip audioClip = AudioClip.Create("wavclip", wav.SampleCount, 1, wav.Frequency, false); audioClip.SetData(wav.LeftChannel, 0); return(audioClip); }
public void onConcatenate(int c) { model.setSound(WAV.Concatenation(c)); if (model.getSound() != null) { view.PlaySound(model.getSound()); } }
private void obtenerDatos2(int id) { byte[] son = new byte[0]; byte[] imagen_personaje = new byte[0]; string conn = "URI=file:" + Application.dataPath + "/Recursos/BD/dbdata.db"; IDbConnection dbconn; dbconn = (IDbConnection) new SqliteConnection(conn); dbconn.Open(); IDbCommand dbcmd = dbconn.CreateCommand(); string sqlQuery; sqlQuery = "select t2.r_color, t2.g_color, t2.b_color, t3.id_personaje, t4.nombre_ubicacion, t3.audio_personaje, t3.imagen_personaje from detalle_aprendizaje as t1 inner join color as t2 on t2.id = t1.id_color inner join personaje as t3 on t1.id_personaje = t3.id_personaje inner join ubicacion as t4 on t1.id_ubicacion = t4.id where t1.id_detalle_apre = " + id; Debug.Log(sqlQuery); dbcmd.CommandText = sqlQuery; IDataReader reader = dbcmd.ExecuteReader(); while (reader.Read()) { id_personaje_2 = reader.GetInt32(3); nombre_ubicacion = reader.GetString(4); son = (byte[])reader["audio_personaje"]; imagen_personaje = (byte[])reader["imagen_personaje"]; Debug.Log(id_personaje_2); if (nombre_ubicacion == "derecha") { id_boton_derecha = id_personaje_2; colorDer.r = reader.GetInt32(0); colorDer.g = reader.GetInt32(1); colorDer.b = reader.GetInt32(2); } else { id_boton_izquierda = id_personaje_2; colorIzq.r = reader.GetInt32(0); colorIzq.g = reader.GetInt32(1); colorIzq.b = reader.GetInt32(2); } } WAV sonido = new WAV(son); audio_personaje_2 = AudioClip.Create("personaje_2", sonido.SampleCount, 1, sonido.Frequency, false, false); audio_personaje_2.SetData(sonido.LeftChannel, 0); if (nombre_ubicacion == "derecha") { texturaDerecha.LoadImage(imagen_personaje); } else { texturaIzquierda.LoadImage(imagen_personaje); } reader.Close(); reader = null; dbcmd.Dispose(); dbcmd = null; dbconn.Close(); }
public void Add(string name, int dataSize, byte[] data) { WAV wav = new WAV(data); AudioClip audioClip = AudioClip.Create(name, wav.SampleCount, wav.ChannelCount, wav.Frequency, false); audioClip.SetData(wav.LeftChannel, 0); wavs.Add(audioClip); //Debug.Log(name+ ": "+wav.ToString()); }
private bool LoadAudio(string path) { DisposeSource(); //Get audio stream _sourceStream = WAV.FromFile(path); _audioSource = path; //Create buffer for stream if (_provider != null) { _buffer = _provider.CreateBuffer(_sourceStream); _buffer.Loop = chkLoop.Checked; } //Set controls _sampleTime = new DateTime((long)_sourceStream.Samples * 10000000 / _sourceStream.Frequency); txtPath.Text = path; lblFrequency.Text = String.Format("{0} Hz", _sourceStream.Frequency); lblSamples.Text = String.Format("{0}", _sourceStream.Samples); customTrackBar1.Value = 0; customTrackBar1.TickStyle = TickStyle.None; customTrackBar1.Maximum = _sourceStream.Samples; customTrackBar1.TickFrequency = _sourceStream.Samples / 8; customTrackBar1.TickStyle = TickStyle.BottomRight; numLoopStart.Maximum = numLoopEnd.Maximum = _sourceStream.Samples; if (!_sourceStream.IsLooping) { numLoopStart.Value = 0; numLoopEnd.Value = _sourceStream.Samples; pnlLoopStart.Width = 0; pnlLoopEnd.Width = 0; } else { numLoopStart.Value = _sourceStream.LoopStartSample; numLoopEnd.Value = _sourceStream.LoopEndSample; } btnOkay.Enabled = true; if (_type == 0) { chkLoopEnable.Checked = true; } UpdateTimeDisplay(); return(true); }
/// <summary> /// Loads an mp3 file /// </summary> /// <param name="file">file path</param> public void LoadMp3File(string file) { LoadedMp3 = false; byte[] data = LoadAudioBytes(file); WAV wav = ConvertMP3DataToWAV(data); _musicSource.clip = ConvertWAVToAudioClip(wav); LoadedMp3 = true; }
public override unsafe void Export(string outPath) { if (outPath.EndsWith(".wav")) { WAV.ToFile(CreateStreams()[0], outPath); } else { base.Export(outPath); } }
public static IEnumerator DesignateMusicFolder(Action onConvertClip) { string path = EditorUtility.OpenFolderPanel("Designate music folder", "", ""); string[] files = Directory.GetFiles(path); DirectoryInfo dirInfo = new DirectoryInfo(path); FileInfo[] fileInfos = dirInfo.GetFiles(); foreach (string fileName in files) { if (fileName.EndsWith(".mp3") || fileName.EndsWith(".wav")) { Debug.Log("Path string is : " + fileName); AudioClip convertedClip = null; // If the file is an mp3, we first convert it to a wav. if (fileName.EndsWith(".mp3")) { WWW www = new WWW(fileName); while (!www.isDone) { yield return(0); } convertedClip = NAudioPlayer.FromMp3Data(fileName); } if (fileName.EndsWith(".wav")) { WAV wav = new WAV(fileName); convertedClip = AudioClip.Create("testSound", wav.SampleCount, 1, wav.Frequency, false); convertedClip.SetData(wav.LeftChannel, 0); } if (convertedClip != null && !SongManager.instance.HasSong(convertedClip)) { AddSongToGlobalManager(convertedClip); } } } if (onConvertClip != null) { onConvertClip(); } yield return(null); //SongChoiceMenu.instance.SpawnCassettesFromSongs(); }
public void onNSampling(int n) { if (model.getSound() != null) { model.setSound(WAV.NSampling(model.getSound(), n)); view.PlaySound(model.getSound()); } else { MessageBox.Show("In order to procced with sampling, please first load wave file."); } }
public async Task SpeakAndWait(string text, AudioSource audioSource = null, int voiceIndex = -1) { specifiedSource = audioSource; synthesizer.Voice = GetVoiceFromIndex(voiceIndex) ?? DefaultVoice; synthesisStream = await synthesizer.SynthesizeTextToStreamAsync(text); byte[] bytes = new byte[synthesisStream.Size]; await synthesisStream.ReadAsync(bytes.AsBuffer(), (uint)synthesisStream.Size, InputStreamOptions.None); wav = new WAV(bytes); samplesReady = true; }
public WAV ConvertToWAV() { if (!_IsDecompressed) { WAVDatas = DecompressDatas(); } bool looping = (loopStart > 0) ? true : false; uint lend = (uint)(size * 1.75); WAV wav = new WAV(From16bTo8b(WAVDatas), 1, 1, 44100, 16, looping, loopStart, lend); return(wav); }
public void SetWavFile(WAV Wave) { if (Wave.Wave.FMT.NrChannel > 2) { byte[] left = Wave.GetChannelData(0); byte[] right = Wave.GetChannelData(1); WAV wav2 = new WAV(SNDUtil.InterleaveChannels(IOUtil.ReadS16sLE(left, 0, left.Length / 2), IOUtil.ReadS16sLE(right, 0, right.Length / 2)), Wave.Wave.FMT.SampleRate, 16, 2); Stream = new WaveFileReader(new MemoryStream(wav2.Write())); } else { Stream = new WaveFileReader(new MemoryStream(Wave.Write())); } Output.Init(Stream); trackBar1.Maximum = (int)Math.Ceiling(Stream.TotalTime.TotalSeconds); }