protected void UpdateAudioDialog_OkButtonClicked(object sender, EventArgs e) { if (Page.IsValid) { if (this.Id > 0) { AudioInfo entity = new AudioInfo(); entity.Id = this.Id; entity.ClassId = Convert.ToInt32(ViewState["ClassId"]); entity.Title = TitleTextBox.Text; entity.Description = DescriptionTextBox.Value; entity.Speakers = SpeakersTextBox.Text; entity.CreatedTimestamp = DateTime.Now; entity.UpdatedTimestamp = DateTime.Now; entity.Visible = UpdateVisibleCheckBox.Checked; //bool result = ClassroomController.UpdateAudio(entity); bool result = AudioInfo.UpdateAudio(entity); if (result) { this.BindDialog(); DataBind(); OnAudioUpdated(EventArgs.Empty); entity = null; Response.Redirect("AudioDetail.aspx?Id=" + this.Id); } } } else { ValidationHelper.SetFocusToFirstError(this.Page, "update_audio"); } }
public static AudioInfo GetStreamInfo(AudioInfo aStream) { MediaInfoContainer mi = new MediaInfoContainer(); try { mi = Processing.GetMediaInfo(aStream.TempFile); } catch (TimeoutException ex) { Log.Error(ex); mi = new MediaInfoContainer(); } finally { if (mi.Audio.Count > 0) { aStream.Bitrate = mi.Audio[0].BitRate; aStream.BitDepth = mi.Audio[0].BitDepth; aStream.ChannelCount = mi.Audio[0].Channels; aStream.SampleRate = mi.Audio[0].SamplingRate; aStream.Format = mi.Audio[0].Format; aStream.FormatProfile = mi.Audio[0].FormatProfile; aStream.StreamSize = Processing.GetFileSize(aStream.TempFile); if (aStream.Format == "PCM") aStream.Length = GetRuntimePCM(aStream); else aStream.Length = mi.Audio[0].Duration/1000d; // convert from ms to seconds } } return aStream; }
private MediaInfo(string ffmpegOutput) { RawData = ffmpegOutput; Audio = new AudioInfo(ffmpegOutput); if (ffmpegOutput.Contains("Video:")) { Video = new VideoInfo(ffmpegOutput); } }
protected void Page_Load(object sender, EventArgs e) { if (this.Id > 0) { //_entity = ClassroomController.GetAudio(this.Id); _entity = AudioInfo.GetAudio(this.Id); } }
//------------------------------------------------------------------------------------------------------------------------ public void AddNewFeed(string audiotoken, AudioInfo audioinfo) { lock (this) { if (!audiopipes.ContainsKey(audiotoken)) audiopipes.Add(audiotoken, audioinfo); else audiopipes[audiotoken] = audioinfo; } }
protected void CreateAudioDialog_OkButtonClicked(object sender, EventArgs e) { if (Page.IsValid) { if (this.ClassId > 0) { // if (FilePathFileUpload.HasFile) //{ AudioInfo entity = new AudioInfo(); //string appPath = Server.MapPath("~/"); //entity.FilePath = @"/App_Resources/Video/" + FilePathFileUpload.FileName; //FilePathFileUpload.SaveAs(appPath + entity.FilePath); //string appPath = Server.MapPath(ConfigurationManager.AppSettings.Get("AudioUploadPath")); //string extension = FilePathFileUpload.PostedFile.FileName.Substring(FilePathFileUpload.PostedFile.FileName.LastIndexOf(".")); //FilePathFileUpload.SaveAs(appPath + entity.FilePath); if (Session["FileName"] != null) { entity.FilePath = Session["FileName"].ToString(); Session["FileName"] = null; } entity.ClassId = this.ClassId; entity.Title = TitleTextBox.Text; entity.Description = DescriptionTextBox.Value; if (SpeakersTextBox.Text != "") { entity.Speakers = SpeakersTextBox.Text; } else { entity.Speakers = null; } entity.Visible = VisibleCheckBox.Checked; entity.CreatedTimestamp = DateTime.Now; entity.UpdatedTimestamp = DateTime.Now; //bool result = ClassroomController.InsertAudio(ref entity); bool result = AudioInfo.InsertAudio(ref entity); if (result) { CreateAudioDialog.Reset(); DataBind(); OnAudioCreated(EventArgs.Empty); entity = null; } } } else { ValidationHelper.SetFocusToFirstError(this.Page, "create_audio"); } }
private void BindDialog() { //_entity = ClassroomController.GetAudio(this.Id); _entity = AudioInfo.GetAudio(this.Id); ViewState["ClassId"] = _entity.ClassId; ViewState["CreatedTime"] = _entity.CreatedTimestamp; DescriptionTextBox.Value = _entity.Description; TitleTextBox.Text = _entity.Title; SpeakersTextBox.Text = _entity.Speakers; UpdateVisibleCheckBox.Checked = _entity.Visible; }
public byte[] GetSample( AudioInfo audioInfo, TimeSpan? timeSpan ) { SampleStruct samples = audioInfo.Samples as SampleStruct; if ( timeSpan != null ) samples.DataPointers = samples.AudioDecoder.GetSamples ( timeSpan.Value ).GetEnumerator (); if ( !samples.DataPointers.MoveNext () ) return null; DataPointer data = samples.DataPointers.Current; DataStream stream = new DataStream ( data.Pointer, data.Size, true, false ); byte [] buffer = new byte [ stream.Length ]; stream.Read ( buffer, 0, ( int ) stream.Length ); return buffer; }
/// <summary> /// Get WAV samples /// </summary> /// <param name="audioInfo">Audio information</param> /// <param name="timeSpan">Audio position (if you need)</param> /// <returns>Audio sample</returns> public byte[] GetSample( AudioInfo audioInfo, TimeSpan? timeSpan ) { SampleInfo sampleInfo = audioInfo.Samples as SampleInfo; if ( timeSpan != null ) audioInfo.AudioStream.Position = sampleInfo.StartPoint + ( int ) ( timeSpan.Value.TotalSeconds * sampleInfo.ByteRate ); if ( ( int ) sampleInfo.DataSize <= ( int ) sampleInfo.Offset ) { return null; } byte [] data = sampleInfo.Reader.ReadBytes ( audioInfo.SampleRate ); sampleInfo.Offset += audioInfo.SampleRate; return data; }
public AudioInfo Decode( Stream stream, params object [] args ) { AudioDecoder decoder = new AudioDecoder ( stream ); AudioInfo audioInfo = new AudioInfo (); audioInfo.AudioChannel = ( AudioChannel ) decoder.WaveFormat.Channels; audioInfo.BitPerSample = decoder.WaveFormat.BitsPerSample / 8; audioInfo.SampleRate = decoder.WaveFormat.SampleRate; audioInfo.AudioStream = stream; audioInfo.AudioDecoder = this; audioInfo.Samples = new SampleStruct () { AudioDecoder = decoder, DataPointers = decoder.GetSamples ().GetEnumerator () }; return audioInfo; }
private static AudioInfo[] LoadAllAudioInfos(string directory) { return Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories).Where(audioPath => { string lrcPath = Path.ChangeExtension(audioPath, ".lrc"); return !CanSkip(audioPath, lrcPath); }).AsParallel().AsOrdered().Select(audioPath => { var audioFile = default(TagLib.File); var audioInfo = new AudioInfo { Path = audioPath }; var tag = default(Tag); try { audioFile = TagLib.File.Create(audioPath); tag = audioFile.Tag; if (Album.HasAlbumInfo(tag)) audioInfo.Album = new Album(tag, true); audioInfo.Track = new Track(tag); } catch (Exception ex) { FastConsole.WriteError("无效音频文件!"); FastConsole.WriteException(ex); return null; } finally { audioFile?.Dispose(); } TrackInfo trackInfo; lock (_database.TrackInfos) trackInfo = _database.TrackInfos.Match(audioInfo.Album, audioInfo.Track); if (!(trackInfo is null)) { audioInfo.TrackInfo = trackInfo; return audioInfo; } // 尝试从数据库获取歌曲 if (The163KeyHelper.TryGetTrackId(tag, out int trackId)) { trackInfo = new TrackInfo(audioInfo.Track, audioInfo.Album, trackId); lock (_database.TrackInfos) _database.TrackInfos.Add(trackInfo); audioInfo.TrackInfo = trackInfo; return audioInfo; } // 尝试从163Key获取ID return audioInfo; }).Where(t => !(t is null)).ToArray(); }
public void LoadPlayingFile(HyPlayItem mpi) { if (Common.GLOBAL["PERSONALFM"].ToString() == "true") { IconPrevious.Glyph = "\uE7E8"; IconPlayType.Glyph = "\uE107"; } else { IconPrevious.Glyph = "\uE892"; IconPlayType.Glyph = "\uE169"; } if (mpi == null) { return; } AudioInfo ai = mpi.AudioInfo; Invoke((async() => { TbSingerName.Text = ai.Artist; TbSongName.Text = ai.SongName; if (mpi.ItemType == HyPlayItemType.Local) { BitmapImage img = new BitmapImage(); await img.SetSourceAsync((await mpi.AudioInfo.LocalSongFile.GetThumbnailAsync(ThumbnailMode.MusicView, 9999))); AlbumImage.Source = img; } else { AlbumImage.Source = new BitmapImage(new Uri(mpi.AudioInfo.Picture)); } SliderAudioRate.Value = HyPlayList.Player.Volume * 100; SliderProgress.Minimum = 0; SliderProgress.Maximum = ai.LengthInMilliseconds; if (mpi.isOnline) { BtnLike.IsChecked = Common.LikedSongs.Contains(mpi.NcPlayItem.sid); } ListBoxPlayList.SelectedIndex = HyPlayList.NowPlaying; TbSongTag.Text = HyPlayList.NowPlayingItem.AudioInfo.tag; })); }
public void PlayBGM(int key, bool loop = true) { if (!OnMusic) { return; } if (audioBGM.ContainsKey(key)) { return; } AudioInfo au = ResManager.Instance.audioTable.GetById(key); if (null == au) { return; } string path = GetAudioClipPath(au); if (string.IsNullOrEmpty(path)) { return; } AudioClip clip = null; ResManager.Instance.LoadAsync <AudioClip>(path, false, true, (ob) => { clip = ob as AudioClip; if (null != clip) { GameObject snd = CreateSoundObject(loop); audioBGM[key] = snd; snd.GetComponent <AudioSource>().clip = clip; snd.GetComponent <AudioSource>().Play(); //snd.audio.PlayOneShot(clip); if (!loop) { StartCoroutine(DestroyAudioCoroutine(key, clip.length)); } } }); }
/// <summary> /// Play Looping Audio at gameobject's position /// </summary> public AudioSource PlayLoopingAudioAtPoint(AudioInfo s, Vector3 pos) { if (s == null || Disabled) { return(null); } GameObject positional_source = allSourceGroups[s.mixerGroup].positionalSourcePooler.RetrieveCopy(); positional_source.transform.position = pos; AudioSource source = positional_source.GetComponent <AudioSource>(); source.volume = s.volumePercentage; source.clip = s.Clip; source.loop = true; source.Play(); return(source); }
void Awake() { stMain main = stTools.stMain; List <AudioSource> audioSources = GetComponents <AudioSource>().ToList(); // add any new audio sources necessary for (int i = audioSources.Count; i < main.audioSources; i++) { audioSources.Add(main.gameObject.AddComponent <AudioSource>()); } // add all AudioSources to audioInfo array audioInfo = new AudioInfo[audioSources.Count]; for (int i = 0; i < audioSources.Count; i++) { audioInfo[i] = new AudioInfo(); audioInfo[i].source = audioSources[i]; audioSources[i].clip = null; } }
public override void Reset(object audioAsset, AudioInfo info) { AudioAsset = audioAsset; m_isStopped = true; m_AudioSource.clip = (AudioClip)AudioAsset; m_AudioSource.time = info.Time; m_AudioSource.spatialBlend = info.SpatialBlend; m_AudioSource.volume = info.Volume; m_AudioSource.pitch = info.Pitch; m_AudioSource.panStereo = info.PanStereo; m_AudioSource.mute = info.Mute; m_AudioSource.loop = info.Loop; m_AudioSource.dopplerLevel = info.DopplerLevel; m_AudioSource.maxDistance = info.MaxDistance; FadeTime = info.FadeTime; AudioId = info.AudioId; Tag = info.Tag; FollowTarget = info.FollowTarget; }
// audio public void OptionsButtonClick() { if (PlayerPrefs.HasKey("AUDIO")) { AudioInfo audioInfo = JsonUtility.FromJson <AudioInfo>(PlayerPrefs.GetString("AUDIO")); audioToggle.isOn = audioInfo.muted; effectsSlider.value = audioInfo.effectsVolume; musicSlider.value = audioInfo.musicVolume; audioSlider.value = audioInfo.audioVolume; } StartCoroutine(pauseToAudioTransition()); //Background.Translate (new Vector3 (0, 6.0f, 0), Space.World); //audioPanel.SetActive (true); //mainUIPanel.SetActive (false); //pausePanel.SetActive (false); }
public void PathInvalidEncodingThrowsException() { var mock = new Mock <ITaggedAudioFile>(); mock.SetupGet(audioFile => audioFile.Info) .Returns(AudioInfo.CreateForLossless("Test", 2, 16, 44100, 100)); using (var ps = PowerShell.Create()) { ps.Runspace = _moduleFixture.Runspace; ps.AddCommand("Export-AudioFile") .AddParameter("Encoder", "Wave") .AddParameter("AudioFile", mock.Object) .AddParameter("Path", "{Invalid}"); Assert.IsType <ArgumentException>( Assert.Throws <CmdletInvocationException>(() => ps.Invoke()) .InnerException); } }
private static PatchResult DuplicateBuildingAudioInfo(string buildingId, string audioInfoId) { BuildingInfo building = PrefabCollection <BuildingInfo> .FindLoaded(buildingId); if (building == null || building.m_customLoopSound == null) { return(PatchResult.NotFound); } // Check if the AudioInfo object has our name, if not, we have to patch it. if (building.m_customLoopSound.name != audioInfoId) { AudioInfo audioInfo = GameObject.Instantiate(building.m_customLoopSound); audioInfo.name = audioInfoId; building.m_customLoopSound = audioInfo; return(PatchResult.Success); } return(PatchResult.AlreadyPatched); }
int GetAudioClipProbIndex(AudioInfo data) { if (null == data) { return(-1); } int count = data.clipPath.Count; if (count <= 0) { return(-1); } float aveProb = 1f / count; float prob = UnityEngine.Random.Range(0f, 1f); return(Mathf.Min(Mathf.FloorToInt(prob / aveProb), count - 1)); }
public AudioInfo ReadAudioInfo(Stream stream) { try { var mp4 = new Mp4Model(stream); mp4.DescendToAtom("moov", "trak", "mdia", "minf", "stbl", "stts"); var stts = new SttsAtom(mp4.ReadAtom(mp4.CurrentAtom)); var sampleCount = stts.PacketCount * stts.PacketSize; mp4.DescendToAtom("moov", "trak", "mdia", "minf", "stbl", "stsd", "mp4a", "esds"); var esds = new EsdsAtom(mp4.ReadAtom(mp4.CurrentAtom)); if (esds.IsAac) { mp4.Reset(); return(AudioInfo.CreateForLossy("AAC", esds.Channels, (int)esds.SampleRate, sampleCount, CalculateBitRate(mp4.GetChildAtomInfo().Single(atom => atom.FourCc.Equals("mdat", StringComparison.Ordinal)).Size, sampleCount, esds.SampleRate))); } // Apple Lossless files have their own atom for storing audio info if (!mp4.DescendToAtom("moov", "trak", "mdia", "minf", "stbl", "stsd", "alac")) { throw new AudioUnsupportedException("Only AAC and ALAC MP4 streams are supported."); } var alac = new AlacAtom(mp4.ReadAtom(mp4.CurrentAtom)); return(AudioInfo.CreateForLossless( "ALAC", alac.Channels, alac.BitsPerSample, (int)alac.SampleRate, sampleCount)); } catch (EndOfStreamException e) { throw new AudioInvalidException(e.Message); } }
public static EffectInfo CreateEffectObject(Transform parent) { EngineSoundEffect defaultEngineSound = VehicleEffectsMod.FindEffect("Aircraft Sound") as EngineSoundEffect; if (defaultEngineSound != null) { GameObject obj = new GameObject(effectName); obj.transform.parent = parent; EngineSoundEffect newEngineSoundEffect = Util.CopyEngineSoundEffect(defaultEngineSound, obj.AddComponent <EngineSoundEffect>()); newEngineSoundEffect.name = effectName; newEngineSoundEffect.m_minPitch = 0.65f; // Create a copy of audioInfo AudioInfo audioInfo = UnityEngine.Object.Instantiate(defaultEngineSound.m_audioInfo) as AudioInfo; audioInfo.name = effectName; audioInfo.m_volume = 0.65f; // Load new audio clip var clip = Util.LoadAudioClipFromModDir("Sounds/prop-plane-moving.ogg"); if (clip != null) { audioInfo.m_clip = clip; } else { return(null); } newEngineSoundEffect.m_audioInfo = audioInfo; return(newEngineSoundEffect); } else { Logging.LogError("Could not find default plane sound effect!"); return(null); } }
public void createStreamingAudio(string url, bool load = true) { string audioName = getFileNameNoSuffix(url, true); if (!mAudioClipList.TryGetValue(audioName, out AudioInfo info)) { info = new AudioInfo(); info.mAudioName = audioName; info.mAudioPath = getFilePath(url); info.mClip = null; info.mState = LOAD_STATE.UNLOAD; info.mIsResource = false; info.mSuffix = getFileSuffix(url); mAudioClipList.Add(audioName, info); } if (load && info.mClip == null) { loadAudio(info, true); } }
private static IEnumerator CoFadeIn(AudioInfo audioInfo, float duration) { audioInfo.source.volume = 0f; audioInfo.source.Play(); var deltaTime = 0f; while (deltaTime < duration) { deltaTime += Time.deltaTime; audioInfo.source.volume += audioInfo.volume * Settings.Instance.volumeMusic * Time.deltaTime / duration; yield return(null); } audioInfo.source.volume = audioInfo.volume * Settings.Instance.volumeMusic; }
/// <summary> /// 创建转码模板 /// </summary> /// <param name="name"></param> /// <param name="container"></param> /// <param name="comment"></param> /// <param name="isFiltrateVideo"></param> /// <param name="isFiltrateAudio"></param> /// <param name="videoInfo"></param> /// <param name="audioInfo"></param> /// <returns></returns> public static CreateTemplateJsonResult CreateTranscodeTemplate(string name, string container, string comment, int isFiltrateVideo, int isFiltrateAudio, VideoInfo videoInfo, AudioInfo audioInfo) { SortedDictionary <string, object> config = new SortedDictionary <string, object>(StringComparer.Ordinal); config["SecretId"] = CosConfig.SECRET_ID; config["SecretKey"] = CosConfig.SECRET_KEY; config["RequestMethod"] = "GET"; config["DefaultRegion"] = "gz"; TencentCloudApiCenter module = new TencentCloudApiCenter(new Vod(), config); SortedDictionary <string, object> requestParams = new SortedDictionary <string, object>(StringComparer.Ordinal); requestParams["name"] = name; requestParams["container"] = container; requestParams["comment"] = comment; requestParams["isFiltrateVideo"] = isFiltrateVideo; requestParams["isFiltrateAudio"] = isFiltrateAudio; requestParams["video"] = videoInfo; requestParams["audio"] = audioInfo; return(module.Call <CreateTemplateJsonResult>("CreateTranscodeTemplate", requestParams)); }
private void ApplyClipChanges(AudioInfo info, bool writeChanges) { Selection.objects = new UnityEngine.Object[] { }; // unselect to get "Apply" to work automatically. var importer = (AudioImporter)AudioImporter.GetAtPath(info._fullPath); importer.compressionBitrate = info._compressionBitrate; importer.forceToMono = info._forceMono; importer.format = info._format; importer.loadType = info._loadType; importer.threeD = info._is3d; AssetDatabase.ImportAsset(info._fullPath, ImportAssetOptions.ForceUpdate); info._hasChanged = true; if (writeChanges) { WriteFile(clipList); } }
private async Task PlayUrlOrQueue(string url, AudioInfo audioInfo) { ulong guildId = Context.Guild.Id; if (!(await IsInVoiceChannel())) { return; } if (!AudioService.IsAudioStreaming(guildId)) { await AudioService.PlayUrl(url, guildId); } else { await ReplyAsync("", embed : EmbedService.MakeFailFeedbackEmbed($"Already streaming audio, queued {audioInfo.ItemInfo.Bold()} item."), lifeTime : Config.FeedbackMessageLifeTime); AudioService.Queue.Push(guildId, audioInfo); } }
/* * public bool IsPlaying(string name) * { * AudioInfo info = audioTable[name] as AudioInfo; * if (info != null) * { * AudioSource audio = info.audio; * if (audio != null) * { * if (!audio.isPlaying) * { * return false; * } * else * { * return true; * } * } * } * return false; * } */ public void PlayAudio(string name) { if (GameApp.GetInstance().GetGameState().MusicOn) { AudioInfo info = audioTable[name] as AudioInfo; if (info != null) { AudioSource audio = info.audio; if (audio != null) { if (Time.time - info.lastPlayingTime > audio.clip.length) { audio.Play(); info.lastPlayingTime = Time.time; } } } } }
public static AudioInfo GetAudioInfo(string sourceName) { AudioInfo audioInfo = null; AggregatedConfig configManager = GlobalData.Instance.AggregatedConfig; if (sourceName == configManager.AudioInfo.AudioSammpleDevice || sourceName == configManager.AudioInfo.DocAudioSammpleDevice) { return(configManager.AudioInfo); } audioInfo = new AudioInfo() { AAC = 64000, SampleRate = 48000, }; return(audioInfo); }
/// <summary> /// 只播Sound类 /// </summary> /// <param name="clip"></param> /// <param name="isLoop"></param> public void Play(AudioClip clip = null, bool isLoop = false) { if (!IsSound) { return; } if (clip == null) { clip = clipClick; } AudioInfo info = GetFreeInfo(); info.source.clip = clip; info.source.loop = isLoop; if (clip == null) { Debug.Log("E播放的音效为空:" + clip); } info.source.Play(); }
/// <summary> /// WAV audio decode /// </summary> /// <param name="stream">WAV file</param> /// <param name="args">argument, don't set this</param> /// <returns>Audio information and PCM data</returns> public AudioInfo Decode( Stream stream, params object [] args ) { AudioInfo audioInfo = new AudioInfo (); BinaryReader br = new BinaryReader ( stream ); int chunkSize; if ( !ReadRIFFHeader ( br, out chunkSize ) ) throw new FileFormatMismatchException (); int byteRate, dataSize; ReadfmtHeader ( br, ref audioInfo, out byteRate ); ReadWaveChunk ( br, ref audioInfo, out dataSize ); ( audioInfo.Samples as SampleInfo ).ByteRate = byteRate; audioInfo.Duration = TimeSpan.FromSeconds ( dataSize / ( float ) byteRate ); audioInfo.AudioStream = stream; audioInfo.AudioDecoder = this; return audioInfo; }
public static EffectInfo CreateEffectObject(Transform parent) { EngineSoundEffect defaultEngineSound = VehicleEffectsMod.FindEffect("Train Movement") as EngineSoundEffect; if (defaultEngineSound != null) { GameObject obj = new GameObject(effectName); obj.transform.parent = parent; EngineSoundEffect steamEngineSound = Util.CopyEngineSoundEffect(defaultEngineSound, obj.AddComponent <EngineSoundEffect>()); steamEngineSound.name = effectName; // Create a copy of audioInfo AudioInfo audioInfo = UnityEngine.Object.Instantiate(defaultEngineSound.m_audioInfo) as AudioInfo; audioInfo.name = effectName; audioInfo.m_volume = 0.7f; // Load new audio clip var clip = Util.LoadAudioClipFromModDir("Sounds/steam-engine-a3-moving.ogg"); if (clip != null) { audioInfo.m_clip = clip; } else { return(null); } steamEngineSound.m_audioInfo = audioInfo; return(steamEngineSound); } else { Logging.LogError("Could not find default train sound effect!"); return(null); } }
/// <summary> /// Gets the sound pack file audio from an audio info. /// </summary> /// <param name="audioInfo">The original audio info.</param> /// <returns>The sound pack file audio.</returns> public static SoundPacksFileV1.Audio GetAudioInfo(AudioInfo audioInfo) { if (audioInfo != null) { var spfAudio = new SoundPacksFileV1.Audio() { Name = audioInfo.name, AudioInfo = new SoundPacksFileV1.AudioInfo() }; Action <AudioInfo, SoundPacksFileV1.AudioInfo> backupAudioInfo = null; backupAudioInfo = new Action <AudioInfo, SoundPacksFileV1.AudioInfo>((ai, spf) => { spf.AudioClip = ai.m_clip; spf.Volume = ai.m_volume; spf.MaxVolume = Mathf.Max(ai.m_volume, 1); spf.Pitch = ai.m_pitch; spf.FadeLength = ai.m_fadeLength; spf.IsLoop = ai.m_loop; spf.Is3D = ai.m_is3D; spf.IsRandomTime = ai.m_randomTime; if (ai.m_variations != null) { spf.Variations = new SoundPacksFileV1.Variation[ai.m_variations.Length]; for (int i = 0; i < ai.m_variations.Length; i++) { spf.Variations[i] = new SoundPacksFileV1.Variation() { Probability = ai.m_variations[i].m_probability, AudioInfo = new SoundPacksFileV1.AudioInfo() }; backupAudioInfo(ai.m_variations[i].m_sound, spf.Variations[i].AudioInfo); } } }); backupAudioInfo(audioInfo, spfAudio.AudioInfo); return(spfAudio); } return(null); }
public void LoadPlayingFile(HyPlayItem mpi) { if (mpi == null) { return; } MediaItemDisplayProperties dp = mpi.MediaItem.GetDisplayProperties(); AudioInfo ai = mpi.AudioInfo; this.Invoke((() => { TbSingerName.Text = ai.Artist; TbSongName.Text = ai.SongName; AlbumImage.Source = mpi.ItemType == HyPlayItemType.Local ? ai.BitmapImage : new BitmapImage(new Uri(ai.Picture)); SliderAudioRate.Value = HyPlayList.Player.Volume * 100; SliderProgress.Minimum = 0; SliderProgress.Maximum = ai.LengthInMilliseconds; ListBoxPlayList.SelectedIndex = (int)HyPlayList.NowPlaying; })); }
public static AudioInfo GetAudioInfo(string sourceName) { AudioInfo audioInfo = null; ILocalDataManager localDataManager = DependencyResolver.Current.GetService <ILocalDataManager>(); ConfigManager configManager = localDataManager.GetSettingConfigData(); if (sourceName == configManager.AudioInfo.AudioSammpleDevice || sourceName == configManager.AudioInfo.DocAudioSammpleDevice) { return(configManager.AudioInfo); } audioInfo = new AudioInfo() { AAC = 64000, SampleRate = 48000, }; return(audioInfo); }
public void TestAppealToTheEmptyAudio() { SendMessageResult sendMessage = mTelegramBot.SendMessage(mChatId, "TestAppealToTheEmptyAudio()"); AudioInfo audio = sendMessage.Result.Audio; ConsoleUtlis.PrintResult(audio); Assert.Multiple(() => { Assert.True(sendMessage.Ok); Assert.IsInstanceOf(typeof(AudioInfo), audio); Assert.IsNull(audio.FileId); Assert.AreEqual(audio.Duration, 0); Assert.IsNull(audio.Performer); Assert.IsNull(audio.Title); Assert.IsNull(audio.MimeType); Assert.AreEqual(audio.FileSize, 0); }); }
public virtual void Process(Audio item, AudioInfo info) { //build amplitude envelope var s = Build(info.Samples); //resample var resampler = Factory.CreateResampler(); var resampled = resampler.Resample(s, info.Samples.Bitrate * ((float)EnvelopeLength / info.Samples.Values.Length)); //build packed array var envelope = new Envelope(resampled); //save into audio item item.Data.Add(envelope); //build volumeDescriptor var volDesc = new VolumeDescriptor(); volDesc.Build(s.Values); item.Data.Add(volDesc); }
// 参数为Sound下的相对路径,并且不带后缀 public void createAudio(string fileName, bool load = true, bool async = true) { string audioName = StringUtility.getFileNameNoSuffix(fileName, true); if (!mAudioClipList.ContainsKey(audioName)) { AudioInfo newInfo = new AudioInfo(); newInfo.mAudioName = audioName; newInfo.mAudioPath = StringUtility.getFilePath(fileName); newInfo.mClip = null; newInfo.mIsResource = true; newInfo.mSuffix = ""; mAudioClipList.Add(audioName, newInfo); } AudioInfo info = mAudioClipList[audioName]; if (load && info.mClip == null) { loadAudio(info, async); } }
public void createStreamingAudio(string url, bool load = true) { string audioName = StringUtility.getFileNameNoSuffix(url, true); if (!mAudioClipList.ContainsKey(audioName)) { AudioInfo newInfo = new AudioInfo(); newInfo.mAudioName = audioName; newInfo.mAudioPath = StringUtility.getFilePath(url); newInfo.mClip = null; newInfo.mIsResource = false; newInfo.mSuffix = StringUtility.getFileSuffix(url); mAudioClipList.Add(audioName, newInfo); } AudioInfo info = mAudioClipList[audioName]; if (load && info.mClip == null) { loadAudio(info, true); } }
void OnAudioListReceived(string name, string list) { string[] lines = System.Text.RegularExpressions.Regex.Split(list, "\n"); foreach (string line in lines) { AudioInfo info = JsonUtility.FromJson <AudioInfo>(line); if (info != null) { int index; if (int.TryParse(Path.GetFileNameWithoutExtension(info.audio), out index)) { if (m_audioBufferList.Contains(index) == false) { m_audioBufferList.Add(index); m_serializer.Request(info.audio); break; } } } } }
private void DoImport() { Initialize(); if (isError) { return; } info = GetInfo(); createClip = true; waitForMainThread.WaitOne(); while (index < info.lengthSamples) { //TODO: issue where end of stream is reached but index < lengthSamples int read = GetSamples(buffer, 0, bufferSize); if (read + index >= info.lengthSamples) { Array.Resize(ref buffer, read); } if (abort) { break; } setData = true; waitForMainThread.WaitOne(); index += read; progress = (float)index / info.lengthSamples; } Cleanup(); }
private bool ReadfmtHeader( BinaryReader br, ref AudioInfo audioInfo, out int byteRate ) { string fmtSignature = Encoding.UTF8.GetString ( br.ReadBytes ( 4 ), 0, 4 ).Trim (); if ( fmtSignature != "fmt" ) { byteRate = 0; return false; } int chunkSize = br.ReadInt32 (); int audioFormat = br.ReadInt16 (); if ( audioFormat != 1 ) { byteRate = 0; return false; } audioInfo.AudioChannel = ( AudioChannel ) br.ReadInt16 (); audioInfo.SampleRate = br.ReadInt32 (); byteRate = br.ReadInt32 (); int blockAlign = br.ReadInt16 (); audioInfo.BitPerSample = br.ReadInt16 () / 8; if ( chunkSize != 16 ) { int extraSize = br.ReadInt16 (); br.ReadBytes ( extraSize ); } return true; }
//protected void EditDescriptionDialog_OkButtonClicked(object sender, EventArgs e) //{ // if (Page.IsValid) // { // if (this.Id > 0) // { // _entity = ClassroomController.GetAudio(this.Id); // _entity.Description = DescriptionTextBox.Value; // _entity.UpdatedTimestamp = DateTime.Now; // UpdateAudioEntity(); // DescriptionUpdatePanel.Update(); // } // } // else // { // ValidationHelper.SetFocusToFirstError(this.Page, "update_audio"); // } //} protected void EditSpeakerDialog_OkButtonClicked(object sender, EventArgs e) { if (Page.IsValid) { if (this.Id > 0) { //_entity = ClassroomController.GetAudio(this.Id); _entity = AudioInfo.GetAudio(this.Id); _entity.Speakers = SpeakersTextBox.Text; _entity.UpdatedTimestamp = DateTime.Now; UpdateAudioEntity(); SpeakerUpdatePanel.Update(); } } else { ValidationHelper.SetFocusToFirstError(this.Page, "update_audio"); } }
/** @brief Return the audio sample information. @return the audio sample information in the AudioInfo structure. */ public AudioInfo QueryInfo() { AudioInfo info = new AudioInfo(); PXCMAudio_QueryInfo(instance, info); return info; }
public override void PlayAudio(AudioInfo ai)// TODO need to queue these if !VoiceManager.CanSpeak() { if (ai != null && ai.clip != null) { SAPISpeechManager.StopListeningFor(ai.clip.length); } base.PlayAudio (ai); }
/// <summary> /// This method will add the variation to a Sound Group during runtime. /// </summary> /// <param name="sType">The name of the Sound Group.</param> /// <param name="clip">The Audio Clip of the variation.</param> /// <param name="variationName">Use this to specify a the variation's name.</param> /// <param name="volume">Use this to specify a the variation's volume.</param> /// <param name="pitch">Use this to specify a the variation's pitch.</param> public static void CreateGroupVariationFromClip(string sType, AudioClip clip, string variationName, float volume = 1f, float pitch = 1f) { if (!SoundsReady) { Debug.LogError("MasterAudio not finished initializing sounds. Cannot create change variation clip yet."); return; } if (!AudioSourcesBySoundType.ContainsKey(sType)) { Debug.LogWarning("Could not locate group '" + sType + "'."); return; } var grp = AudioSourcesBySoundType[sType]; var matchingNameFound = false; // ReSharper disable once ForCanBeConvertedToForeach for (var i = 0; i < grp.Sources.Count; i++) { var aVar = grp.Sources[i]; if (aVar.Variation.name != variationName) { continue; } matchingNameFound = true; break; } if (matchingNameFound) { LogWarning("You already have a Variation for this Group named '" + variationName + "'. \n\nPlease rename these Variations when finished to be unique, or you may not be able to play them by name if you have a need to."); } // ReSharper disable once ArrangeStaticMemberQualifier var newVar = (GameObject) GameObject.Instantiate(Instance.soundGroupVariationTemplate.gameObject, grp.Group.transform.position, Quaternion.identity); newVar.transform.name = variationName; newVar.transform.parent = grp.Group.transform; var audSrc = newVar.GetComponent<AudioSource>(); audSrc.clip = clip; audSrc.pitch = pitch; var newVariation = newVar.GetComponent<SoundGroupVariation>(); if (newVariation.VariationUpdater != null) { newVariation.DisableUpdater(); } var newInfo = new AudioInfo(newVariation, newVariation.VarAudio, volume); grp.Sources.Add(newInfo); if (!_randomizer.ContainsKey(sType)) { return; // sanity check } _randomizer[sType].Add(grp.Sources.Count - 1); _randomizerLeftovers[sType].Add(grp.Sources.Count - 1); }
private static PlaySoundResult PlaySoundIfAvailable(string soundGroupName, AudioInfo info, Vector3 sourcePosition, float volumePercentage, ref bool forgetSoundPlayed, float? pitch = null, AudioGroupInfo audioGroup = null, Transform sourceTrans = null, bool attachToSource = false, float delaySoundTime = 0f, bool useVector3 = false, bool makePlaySoundResult = false, bool isChaining = false, bool isSingleSubscribedPlay = false) { if (info.source == null) { // this avoids false errors when stopping the game (from became "invisible" event callers) return null; } MasterAudioGroup maGroup = audioGroup._group; if (maGroup.curVariationMode == MasterAudioGroup.VariationMode.Normal && info.source.audio.isPlaying) { var playedPercentage = AudioUtil.GetAudioPlayedPercentage(info.source); var retriggerPercent = maGroup.retriggerPercentage; if (playedPercentage < retriggerPercent) { return null; // wait for this to stop playing or play further. } } info.variation.Stop(); info.variation.ObjectToFollow = null; if (useVector3) { info.source.transform.position = sourcePosition; if (MasterAudio.Instance.prioritizeOnDistance) { AudioPrioritizer.Set3dPriority(info.source); } } else if (sourceTrans != null) { if (attachToSource) { info.variation.ObjectToFollow = sourceTrans; } else { info.source.transform.position = sourceTrans.position; info.variation.ObjectToTriggerFrom = sourceTrans; } if (MasterAudio.Instance.prioritizeOnDistance) { AudioPrioritizer.Set3dPriority(info.source); } } else { // "2d manner" - from Master Audio location if (MasterAudio.Instance.prioritizeOnDistance) { AudioPrioritizer.Set2dSoundPriority(info.source); } info.source.transform.localPosition = Vector3.zero; // put it back in MA prefab position after being detached. } var groupVolume = maGroup.groupMasterVolume; var busVolume = GetBusVolume(maGroup); float calcVolume = info.originalVolume * groupVolume * busVolume * MasterAudio.Instance.masterAudioVolume; // set volume to percentage. float volume = calcVolume * volumePercentage; var targetVolume = volume; var randomVol = 0f; if (info.variation.useRandomVolume) { // random volume randomVol = UnityEngine.Random.Range(info.variation.randomVolumeMin, info.variation.randomVolumeMax); switch (info.variation.randomVolumeMode) { case SoundGroupVariation.RandomVolumeMode.AddToClipVolume: targetVolume += randomVol; break; case SoundGroupVariation.RandomVolumeMode.IgnoreClipVolume: targetVolume = randomVol; break; } } info.source.audio.volume = targetVolume; // save these for on the fly adjustments afterward info.lastPercentageVolume = volumePercentage; info.lastRandomVolume = randomVol; bool isActive = false; #if UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 isActive = info.source.audio.gameObject.active; #else isActive = info.source.audio.gameObject.activeInHierarchy; #endif if (!isActive) { return null; } PlaySoundResult result = null; if (makePlaySoundResult) { result = new PlaySoundResult(); result.ActingVariation = info.variation; if (delaySoundTime > 0f) { result.SoundScheduled = true; } else { result.SoundPlayed = true; } } else { forgetSoundPlayed = true; } var playSoundParams = new SoundGroupVariation.PlaySoundParams(maGroup.name, volumePercentage, targetVolume, pitch, sourceTrans, attachToSource, delaySoundTime, maGroup.curVariationMode == MasterAudioGroup.VariationMode.LoopedChain, isSingleSubscribedPlay); if (playSoundParams.isChainLoop && !isChaining) { maGroup.ChainLoopCount = 0; } if (playSoundParams.isChainLoop) { // make sure there isn't 2 going, ever MasterAudio.StopAllOfSound(playSoundParams.soundType); } info.variation.Play(pitch, targetVolume, playSoundParams); return result; }
public static AudioInfo ToAudioInfo(this DataRow dr) { AudioInfo a = new AudioInfo(); a.Id = dr.GetInt("ID"); a.Id = dr.GetInt("ID"); a.ClassId = dr.GetInt("ClassId"); a.Title = dr.GetString("Title"); a.Description = dr.GetString("Description"); a.FilePath = dr.GetString("FilePath"); if (!dr.IsNull("Speakers")) a.Speakers = dr.GetString("Speakers"); a.Visible = dr.GetBoolean("Visible", true); a.CreatedTimestamp = dr.GetDate("CreatedTimestamp"); a.UpdatedTimestamp = dr.GetDate("UpdatedTimestamp"); return a; }
protected void BindPage() { //_entity = ClassroomController.GetAudio(this.AudioId); _entity = AudioInfo.GetAudio(this.AudioId); if (_entity != null) { litTitle.Text = _entity.Title; litDescription.Text = _entity.Description; //_filePath = ConfigurationManager.AppSettings["VideoUploadPath"].ToString() + _entity.FilePath; _filePath = "Media/" + _entity.FilePath ; } }
protected void DeleteAudioButton_Click(object sender, EventArgs e) { //ClassroomController.DeleteAudio(this.Id); AudioInfo.DeleteAudio(this.Id); Response.Redirect("Audios.aspx?ClassId=" + Convert.ToInt32(ViewState["ClassId"])); _entity = null; }
protected void EditFilePathDialog_OkButtonClicked(object sender, EventArgs e) { if (Page.IsValid) { if (this.Id > 0) { //_entity = ClassroomController.GetAudio(this.Id); _entity = AudioInfo.GetAudio(this.Id); //_entity.FilePath = FilePathFileUpload. _entity.UpdatedTimestamp = DateTime.Now; UpdateAudioEntity(); FilePathUpdatePanel.Update(); } } else { ValidationHelper.SetFocusToFirstError(this.Page, "update_audio"); } }
public virtual void QueueAudioGap( float time, string charName=null ) { if ( AudioQueue == null ) AudioQueue = new Queue<AudioInfo>(); AudioInfo ai = new AudioInfo(); ai.time = time; ai.name = charName; ai.source = audioSource; if (charName != null && characterAudioSources.ContainsKey (charName)) ai.source = characterAudioSources[charName]; // could check and use audioScource AudioQueue.Enqueue(ai); }
public void QueueAudio(AudioClip clip, string charName=null) { if ( AudioQueue == null ) AudioQueue = new Queue<AudioInfo>(); // create new info AudioInfo ai = new AudioInfo(); ai.clip = clip; ai.time = 0.0f; ai.name = charName; if ( charName != null ) ai.source = GetAudioSource(charName); // add to queue AudioQueue.Enqueue(ai); }
// ReSharper disable once FunctionComplexityOverflow private static PlaySoundResult PlaySoundIfAvailable(AudioInfo info, Vector3 sourcePosition, float volumePercentage, ref bool forgetSoundPlayed, float? pitch = null, AudioGroupInfo audioGroup = null, Transform sourceTrans = null, bool attachToSource = false, float delaySoundTime = 0f, bool useVector3 = false, bool makePlaySoundResult = false, bool isChaining = false, bool isSingleSubscribedPlay = false) { if (info.Source == null) { // this avoids false errors when stopping the game (from became "invisible" event callers) return null; } // ReSharper disable once PossibleNullReferenceException var maGroup = audioGroup.Group; if (maGroup.curVariationMode == MasterAudioGroup.VariationMode.Normal && info.Source.isPlaying) { var playedPercentage = AudioUtil.GetAudioPlayedPercentage(info.Source); var retriggerPercent = maGroup.retriggerPercentage; if (playedPercentage < retriggerPercent) { return null; // wait for this to stop playing or play further. } } info.Variation.Stop(); info.Variation.ObjectToFollow = null; var shouldUseClipAgePriority = Instance.prioritizeOnDistance && (Instance.useClipAgePriority || info.Variation.ParentGroup.useClipAgePriority); if (useVector3) { info.Source.transform.position = sourcePosition; if (Instance.prioritizeOnDistance) { AudioPrioritizer.Set3DPriority(info.Source, shouldUseClipAgePriority); } } else if (sourceTrans != null) { if (attachToSource) { info.Variation.ObjectToFollow = sourceTrans; } else { info.Source.transform.position = sourceTrans.position; info.Variation.ObjectToTriggerFrom = sourceTrans; } if (Instance.prioritizeOnDistance) { AudioPrioritizer.Set3DPriority(info.Source, shouldUseClipAgePriority); } } else { // "2d manner" - from Master Audio location if (Instance.prioritizeOnDistance) { AudioPrioritizer.Set2DSoundPriority(info.Source); } info.Source.transform.localPosition = Vector3.zero; // put it back in MA prefab position after being detached. } var groupVolume = maGroup.groupMasterVolume; var busVolume = GetBusVolume(maGroup); var varVol = info.OriginalVolume; var randomVol = 0f; if (info.Variation.useRandomVolume) { // random volume randomVol = UnityEngine.Random.Range(info.Variation.randomVolumeMin, info.Variation.randomVolumeMax); switch (info.Variation.randomVolumeMode) { case SoundGroupVariation.RandomVolumeMode.AddToClipVolume: varVol += randomVol; break; case SoundGroupVariation.RandomVolumeMode.IgnoreClipVolume: varVol = randomVol; break; } } var calcVolume = varVol * groupVolume * busVolume * Instance._masterAudioVolume; // set volume to percentage. var volume = calcVolume * volumePercentage; var targetVolume = volume; info.Source.volume = targetVolume; // save these for on the fly adjustments afterward info.LastPercentageVolume = volumePercentage; info.LastRandomVolume = randomVol; // ReSharper disable once JoinDeclarationAndInitializer bool isActive; #if UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 isActive = info.Variation.GameObj.active; #else isActive = info.Variation.GameObj.activeInHierarchy; #endif if (!isActive) { return null; } PlaySoundResult result = null; if (makePlaySoundResult) { result = new PlaySoundResult { ActingVariation = info.Variation }; if (delaySoundTime > 0f) { result.SoundScheduled = true; } else { result.SoundPlayed = true; } } else { forgetSoundPlayed = true; } var soundType = maGroup.GameObjectName; var isChainLoop = maGroup.curVariationMode == MasterAudioGroup.VariationMode.LoopedChain; if (isChainLoop) { if (!isChaining) { maGroup.ChainLoopCount = 0; } var objFollow = info.Variation.ObjectToFollow; // make sure there isn't 2 chains going, ever! if (maGroup.ActiveVoices > 0 && !isChaining) { StopAllOfSound(soundType); } // restore this because it is lost from the Stop above; info.Variation.ObjectToFollow = objFollow; } info.Variation.Play(pitch, targetVolume, soundType, volumePercentage, targetVolume, pitch, sourceTrans, attachToSource, delaySoundTime, isChaining, isSingleSubscribedPlay); return result; }
/// <summary> /// AC3 encode processing function, called by BackgroundWorker thread /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void DoEncodeAc3(object sender, DoWorkEventArgs e) { _bw = (BackgroundWorker)sender; bool use64BitEncoder = AppSettings.Use64BitEncoders && AppSettings.Ffmpeg64Installed && Environment.Is64BitOperatingSystem; int[] sampleRateArr = new[] {0, 8000, 11025, 22050, 44100, 48000}; int[] channelArr = new[] {0, 2, 3, 4, 1}; string status = Processing.GetResourceString("ffmpeg_encoding_audio_status"); _bw.ReportProgress(-10, status); _bw.ReportProgress(0, status); AudioInfo item = _jobInfo.AudioStreams[_jobInfo.StreamId]; int outChannels = -1; int outSampleRate = -1; switch (_jobInfo.AudioProfile.Type) { case ProfileType.AC3: outChannels = ((AC3Profile) _jobInfo.AudioProfile).OutputChannels; outChannels = channelArr[outChannels]; if (item.ChannelCount > 6) outChannels = 6; outSampleRate = ((AC3Profile) _jobInfo.AudioProfile).SampleRate; outSampleRate = sampleRateArr[outSampleRate]; break; case ProfileType.Copy: outChannels = item.ChannelCount > 6 ? 6 : item.ChannelCount; outSampleRate = item.SampleRate; if (_jobInfo.EncodingProfile.OutFormat == OutputType.OutputDvd && outSampleRate != 48000) outSampleRate = 48000; break; } string inputFile = AviSynthGenerator.GenerateAudioScript(item.TempFile, item.Format, item.FormatProfile, item.ChannelCount, outChannels, item.SampleRate, outSampleRate); string outFile = Processing.CreateTempFile(item.TempFile, "encoded.ac3"); string localExecutable = Path.Combine(AppSettings.ToolsPath, use64BitEncoder ? Executable64 : Executable); DateTime startTime = DateTime.Now; using (Process encoder = new Process(), decoder = BePipe.GenerateProcess(inputFile)) { ProcessStartInfo encoderParameter = new ProcessStartInfo(localExecutable) { WorkingDirectory = AppSettings.DemuxLocation, Arguments = FfmpegCommandLineGenerator.GenerateAC3EncodeLine( _jobInfo, "-", outFile), CreateNoWindow = true, UseShellExecute = false, RedirectStandardError = true, RedirectStandardInput = true }; encoder.StartInfo = encoderParameter; _localItem = item; _encodingStart = startTime; encoder.ErrorDataReceived += Ac3EncodeOnErrorDataReceived; Log.InfoFormat("ffmpeg {0:s}", encoderParameter.Arguments); bool encStarted; bool decStarted; try { encStarted = encoder.Start(); } catch (Exception ex) { encStarted = false; Log.ErrorFormat("ffmpeg exception: {0}", ex); _jobInfo.ExitCode = -1; } try { decStarted = decoder.Start(); } catch (Exception ex) { decStarted = false; Log.ErrorFormat("bepipe exception: {0}", ex); _jobInfo.ExitCode = -1; } if (encStarted && decStarted) { encoder.PriorityClass = AppSettings.GetProcessPriority(); encoder.BeginErrorReadLine(); decoder.PriorityClass = AppSettings.GetProcessPriority(); Processing.CopyStreamToStream(decoder.StandardOutput.BaseStream, encoder.StandardInput.BaseStream, 32768, (src, dst, exc) => { src.Close(); dst.Close(); if (exc == null) return; Log.Debug(exc.Message); Log.Debug(exc.StackTrace); }); while (!encoder.HasExited) { if (_bw.CancellationPending) { encoder.Kill(); decoder.Kill(); } Thread.Sleep(200); } encoder.WaitForExit(10000); encoder.CancelErrorRead(); decoder.WaitForExit(10000); _jobInfo.ExitCode = encoder.ExitCode; Log.InfoFormat("Exit Code: {0:g}", _jobInfo.ExitCode); if (_jobInfo.ExitCode == 0) { _jobInfo.TempFiles.Add(inputFile); _jobInfo.TempFiles.Add(item.TempFile); _jobInfo.TempFiles.Add(item.TempFile + ".d2a"); _jobInfo.TempFiles.Add(item.TempFile + ".ffindex"); item.TempFile = outFile; AudioHelper.GetStreamInfo(item); } } } _bw.ReportProgress(100); _jobInfo.CompletedStep = _jobInfo.NextStep; e.Result = _jobInfo; }
public virtual void PlayAudio(AudioInfo ai)// TODO need to queue these if !VoiceManager.CanSpeak() { if (ai.clip) { #if DEBUG_BRAIN UnityEngine.Debug.Log("Brain.PlayAudio() : play <" + ai.clip.name + ">"); #endif if ( ai.source != null ){ ai.source.clip = ai.clip; ai.source.Play(); } else Camera.mainCamera.audio.PlayOneShot(ai.clip); } }
public static double GetRuntimePCM(AudioInfo item) { return (item.StreamSize * 8D) / item.ChannelCount / ((double)item.SampleRate * item.BitDepth); }
public void CheckAudioQueue() // need to make this queue per character. { if ( AudioQueue == null ) return; if (!VoiceMgr.CanSpeak()) return; // don't process the queue while the player is speaking // check to see if we're allowed to play if ( AudioQueueTime < Time.time ) { if ( AudioQueue.Count > 0 ) { // get next audio to play AudioInfo ai = AudioQueue.Dequeue(); // set current CurrentAudioInfo = ai; if ( ai.clip != null ) { // get the audio time AudioQueueTime = Time.time + ai.clip.length; // now play it PlayAudio(ai); } else { // this is just an audio gap AudioQueueTime = Time.time + ai.time; CurrentAudioInfo = null; } } else CurrentAudioInfo = null; } }
/// <summary> /// This method will add the variation to a Sound Group during runtime. /// </summary> /// <param name="sType">The name of the Sound Group.</param> /// <param name="clip">The Audio Clip of the variation.</param> /// <param name="variationName">Use this to specify a the variation's name.</param> /// <param name="volume">Use this to specify a the variation's volume.</param> /// <param name="pitch">Use this to specify a the variation's pitch.</param> public static void CreateGroupVariationFromClip(string sType, AudioClip clip, string variationName, float volume = 1f, float pitch = 1f) { if (!SoundsReady) { Debug.LogError("MasterAudio not finished initializing sounds. Cannot create change variation clip yet."); return; } if (!audioSourcesBySoundType.ContainsKey(sType)) { Debug.LogWarning("Could not locate group '" + sType + "'."); return; } var grp = audioSourcesBySoundType[sType]; var matchingNameFound = false; for (var i = 0; i < grp._sources.Count; i++) { var aVar = grp._sources[i]; if (aVar.variation.name == variationName) { matchingNameFound = true; break; } } if (matchingNameFound) { MasterAudio.LogWarning("You already have a Variation for this Group named '" + variationName + "'. \n\nPlease rename these Variations when finished to be unique, or you may not be able to play them by name if you have a need to."); } var newVar = (GameObject) GameObject.Instantiate(MasterAudio.Instance.soundGroupVariationTemplate.gameObject, grp._group.transform.position, Quaternion.identity); newVar.transform.name = variationName; newVar.transform.parent = grp._group.transform; newVar.audio.clip = clip; newVar.audio.pitch = pitch; var newVariation = newVar.GetComponent<SoundGroupVariation>(); var newInfo = new AudioInfo(newVariation, newVar.audio, volume); grp._sources.Add(newInfo); if (randomizer.ContainsKey(sType)) { // sanity check randomizer[sType].Add(grp._sources.Count - 1); } }
private void BindDialog() { //_entity = ClassroomController.GetAudio(this.Id); _entity = AudioInfo.GetAudio(this.Id); ViewState["ClassId"] = _entity.ClassId; }