public AudioClip chooseNewMusic(MusicType nextMusicType) { AudioClip nextMusicToPlay = null; int index = 0; switch (nextMusicType) { case MusicType.MainTitle: nextMusicToPlay = mainTitleMusic; break; case MusicType.Starmap: index = Random.Range(0, starmapMusics.Length); nextMusicToPlay = starmapMusics[index]; break; case MusicType.BattlezoneCalm: index = Random.Range(0, battlezoneCalmMusics.Length); nextMusicToPlay = battlezoneCalmMusics[index]; break; case MusicType.BattlezonHostile: index = Random.Range(0, battlezoneHostileMusics.Length); nextMusicToPlay = battlezoneHostileMusics[index]; break; case MusicType.BattlezoneAction: index = Random.Range(0, battlezoneActionMusics.Length); nextMusicToPlay = battlezoneActionMusics[index]; break; } return(nextMusicToPlay); }
public void ChangeMusic(MusicType type, float fadeSeconds) { StopAllCoroutines(); AudioSource newMusic = GetAudioSource(type); StartCoroutine(CrossFade(newMusic, fadeSeconds)); }
public void ChangeMusicType(MusicType newType) { AudioSource newSource = getAudioSource(newType); StartCoroutine(crossfade(currentSource, newSource)); currentSource = newSource; }
public IActionResult Upd(int id, [FromBody] MusicType mt) { try { if (id < 1) { throw new IndexOutOfRangeException("ID must be greater than 0 (" + where + ") (UPD)"); } if (mt is null) { throw new ArgumentNullException("Music Type Object Empty (" + where + ") (UPD)"); } if (mt.Name.Length == 0) { throw new DataException("Music Type NAme can't be BLANK (" + where + ") (UPD)"); } SM.MusicType mto = new SM.MusicType(id, mt.Name); bool UpdOk = S.ServiceLocator.Instance.MusicTypeService.Upd(mto); return(ApiControllerHelper.SendOk(this, new ApiResult <bool>(HttpStatusCode.OK, null, UpdOk), HttpStatusCode.OK)); } catch (Exception ex) { return(ApiControllerHelper.SendError(this, ex)); } }
//Used if running the game in a single scene, takes an integer music source allowing you to choose a clip by number and play. public void PlaySelectedMusic(MusicType musicType) { //This switch looks at the integer parameter musicChoice to decide which music clip to play. switch (musicType) { //if musicChoice is 0 assigns titleMusic to audio source case MusicType.MainMenu: musicSource.clip = menuMusic; break; //if musicChoice is 1 assigns mainMusic to audio source case MusicType.Game: musicSource.clip = gameMusic; break; case MusicType.Victory: musicSource.clip = menuMusic; break; default: musicSource.clip = menuMusic; break; } //Play the selected clip musicSource.Play(); }
// Play a music track if it is not already playing public static void PlayMusic(MusicType type, bool isResetting = false) { if (IsInvalid()) { return; } // Find the sound with the given name foreach (MusicMapping mapping in Instance.MusicList) { if (mapping.Name == type && mapping.AudioClip != null && (Instance._musicSource.clip != mapping.AudioClip || isResetting)) { // Audio was found, so play it Debug.Log("SoundController.PlayMusic(): name: " + mapping.Name + ", audio: " + mapping.AudioClip); Instance._musicSource.clip = mapping.AudioClip; Instance._musicSource.Play(); // Reset music volume _isFadingOutMusic = false; Instance._musicSource.volume = MUSIC_VOLUME; return; } } }
/// <summary> /// Finds the gig by gig identifier. /// The gig is stored in context and the request is redirected /// to ShowGigByAccID which will show it. /// </summary> /// <param name="gigIdentifier">The gig identifier.</param> private void FindGigByGigIdentifier(int gigIdentifier) { try { #region Unity /* Get the Service */ IUnityContainer container = (IUnityContainer)HttpContext.Current.Application["unityContainer"]; IGigService gigService = container.Resolve <IGigService>(); Gig gig = gigService.FindGig(gigIdentifier); MusicType musicType = gigService.FindMusicType(gig.typeId); #endregion #region Delegate on factories ///* Create an "GigService". */ //IGigService gigService = GigServiceFactory.GetService(); ///* Get Gig Data */ //GigVO gig = gigService.FindGig(gigIdentifier); #endregion /* Attach data to context */ Context.Items.Add("gig", gig); Context.Items.Add("musicType", musicType); /* Redirect to Visualization WebForm */ Server.Transfer(Response.ApplyAppPathModifier("./ShowGigByGigID.aspx")); } catch (InstanceNotFoundException) { lblIdentifierError.Visible = true; } }
void PlayMusic(MusicType inMusicType) { StopAllCoroutines(); switch (inMusicType) { case MusicType.None: { Debug.LogWarning("fading music"); StartCoroutine(FadeMusic()); break; } case MusicType.Menu: { currentMusic = MusicType.Menu; audioSource.loop = true; audioSource.clip = menuLoop; audioSource.Play(); break; } case MusicType.Game: { currentMusic = MusicType.Game; audioSource.loop = false; audioSource.clip = gameStart; audioSource.Play(); StartCoroutine(PlayMusicDelayed(gameLoop, gameStart.length)); break; } } }
private AudioSource GetAudioSource(MusicType type) { switch (type) { case MusicType.MAIN_MENU: return(mainMenuMusic); case MusicType.INTRO: return(introMusic); case MusicType.CREDITS: return(creditsMusic); case MusicType.LEVEL_01: return(level01Music); case MusicType.LEVEL_BOSS_01: return(levelBoss01Music); case MusicType.LEVEL_BOSS_02: return(levelBoss02Music); case MusicType.LEVEL_BOSS_03: return(levelBoss03Music); case MusicType.LEVEL_BOSS_04: return(levelBoss04Music); default: return(level01Music); } }
IEnumerator PlayMusic(MusicType _type, float _length) { yield return(new WaitForSeconds(_length)); Source.Stop(); int _Tune = 0; switch (_type) { case MusicType.Menus: _Tune = Random.Range(0, MenuClips.Count); Source.PlayOneShot(MenuClips[_Tune]); StartCoroutine(PlayMusic(MusicType.Menus, MenuClips[_Tune].length)); break; case MusicType.Other: _Tune = Random.Range(0, OtherClips.Count); Source.PlayOneShot(OtherClips[_Tune]); StartCoroutine(PlayMusic(MusicType.Other, OtherClips[_Tune].length)); break; case MusicType.InGame: _Tune = Random.Range(0, InGameClips.Count); Source.PlayOneShot(InGameClips[_Tune]); StartCoroutine(PlayMusic(MusicType.InGame, InGameClips[_Tune].length)); break; } }
public static void PlayMusic(MusicType mt) { if (instance != null) { AudioClip clip; switch (mt) { case MusicType.Bug: { clip = instance.bugMusic; break; } case MusicType.Ghost: { clip = instance.ghostMusic; break; } default: { clip = instance.menuMusic; break; } } if (instance != null) { instance.audio.Stop(); instance.audio.clip = clip; instance.audio.Play(); } } }
public void PlayUIMusic(MusicType type, bool useFadeOut = true) { var track = tracks?.Find(s => s.type == type); var clip = track?.clip; if (clip == null) { Debug.Log($"Can't find clip with type \"{type.ToString()}\" in UISoundManager"); return; } if (_currentMusic != null && _currentMusic == track) { return; } _currentMusic = track; if (useFadeOut && UIMusicPlayer.isPlaying) { _isFadingOut = true; return; } _isFadingOut = false; StartUIMusic(); }
public void PlayMusic(MusicType type) { if (isMuteMusic) { return; } if (this.type == type && musicAudio.clip != null) { musicAudio.Play(); } else { this.type = type; switch (type) { case MusicType.HomeMusic: musicAudio.clip = homeMusic; musicAudio.loop = true; musicAudio.Play(); break; case MusicType.IngameMusic: musicAudio.clip = ingameMusic; musicAudio.loop = true; musicAudio.Play(); break; } } }
public void StopMusic(MusicType musicType) { if (CanPlayMusic() && this.controller) { this.controller.StopMusic(musicType); } }
public MovieScreen(byte[] movieData, MusicType music, Screen nextScreen) { this.music = music; this.nextScreen = nextScreen; moviePlayer = new MoviePlayer(movieData, OnMovieFinished); AddControl(moviePlayer); }
internal void PlayMusic(MusicType audioName) { if (audioName == MusicType.Mute) { musicSource.Type = audioName; musicSource.Source.Stop(); return; } if (musics.TryGetValue(audioName.ToString(), out AudioClip clip)) { Debug.Log($"Play Music {audioName}!"); if (musicSource.Type == audioName && musicSource.Source.isPlaying) { return; } musicSource.Type = audioName; musicSource.Source.clip = clip; musicSource.Source.loop = true; musicSource.Source.Play(); } else { Debug.LogWarning($"Music {audioName} not found!"); } }
void Update() { if (isCrossFading) { if (mainTimer < 1) { mainTimer += Time.unscaledDeltaTime / mainDuration; currentMusic.MainAudioSource.volume = Mathf.Lerp(mainOriginalVolume, mainTargetVolume, mainTimer); } if (secondaryTimer < 1) { secondaryTimer += Time.unscaledDeltaTime / secondaryDuration; currentMusic.SecondaryAudioSource.volume = Mathf.Lerp(secondaryOriginalVolume, secondaryTargetVolume, secondaryTimer); } if (mainTimer >= 1 && secondaryTimer >= 1) { isCrossFading = false; currentMusic.MainAudioSource.volume = mainTargetVolume; currentMusic.SecondaryAudioSource.volume = secondaryTargetVolume; if (state == MusicType.Main) { state = MusicType.Secondary; } else { state = MusicType.Main; } } } }
public static MusicType GetMusicType(string Mtype) { MusicType musicType = new MusicType(); switch (Mtype) { case "HipHop": musicType = MusicType.HipHop; break; case "Metal": musicType = MusicType.Metal; break; case "Rock": musicType = MusicType.Rock; break; case "Jazzrapbreakbeat": musicType = MusicType.Jazzrapbreakbeat; break; case "Classic": musicType = MusicType.Classic; break; } return(musicType); }
public void FadeInMusic(MusicType type, float fadeSeconds) { StopAllCoroutines(); EnsureAllMusicsStopped(); currentMusic = GetAudioSource(type); StartCoroutine(FadeMusic(fadeSeconds, true)); }
public void PlayMusic(string musicName, MusicType musicType) { switch (musicType) { case MusicType.BGM: if (bkMusicDict.Count <= 0) { return; } AudioClip bkclip = bkMusicDict[musicName].audioClip; if (bkclip != null && bgmPlayer.clip != bkclip) { bgmPlayer.clip = bkclip; bgmPlayer.Play(); } break; case MusicType.HumanSound: if (hmEffectDict.Count <= 0) { return; } AudioClip hmclip = hmEffectDict[musicName].audioClip; if (hmclip != null) { humanSoundPlayer.clip = hmclip; } humanSoundPlayer.Play(); break; } }
//---------a public function used by game managers to change the music type //---------according to the condition. public void ChangeMusic(MusicType _musicType) { //pause the currently playing music to prevent multiple audio clips playing at the same time this._audioSource.Pause(); this._audioSource.clip = _audioClips[_musicType]; this._audioSource.Play(); }
public void PlayMusic(MusicType type) { // Handles the playing of Music for pages & windows // Returns: nothing // Params: // - MusicType type : provides which music should be played switch (type) { // Handles music playing for Main Menu case MusicType.MainMenu: MusicPlayer.Open(new Uri("..\\..\\Resources\\bensound-evolution.wav", UriKind.Relative)); // .wav file from bensound.com break; // Handles music playing for Difficulty Menu case MusicType.DifficultyMenu: MusicPlayer.Open(new Uri("..\\..\\Resources\\Actionable.wav", UriKind.Relative)); // .wav file from bensound.com break; // Handles music playing during gameplay case MusicType.Game: MusicPlayer.Open(new Uri("..\\..\\Resources\\bensound-epic.wav", UriKind.Relative)); // .wav file from from bensound.com break; } // Pause the sound once loaded, set it's volume, unmute it, start it from the beginning, then play it. MusicPlayer.Pause(); MusicPlayer.Volume = 0.18; MusicPlayer.IsMuted = Muted; MusicPlayer.Position = new TimeSpan(0); MusicPlayer.Play(); }
// Play music (change track). public void PlayMusic(MusicType musicType) { CurrentMusicType = musicType; AudioClip musicClip = IntroMusic; switch (musicType) { case MusicType.Intro: { musicClip = IntroMusic; break; } case MusicType.Game: { musicClip = GameMusic; break; } case MusicType.Outro: { musicClip = OutroMusic; break; } } MusicPlayer.clip = musicClip; MusicPlayer.Play(); }
internal static GM.MusicType ToGlobal(this MusicType mt) { return(new GM.MusicType() { Id = mt.Id, Name = mt.Name }); }
public MusicDevice(IMusicPluginObject musicPlugin, string name, MusicType mt) { _musicDriverName = musicPlugin.Name; _musicDriverId = musicPlugin.Id; _name = name; _type = mt; Handle = new DeviceHandle(CompleteId.GetHashCode()); }
public void PlayVillage() { currentBGM = MusicType.village; audio.Stop(); audio.clip = villageBgm; audio.loop = true; audio.Play(); }
public override void ResetEffects() { if (!AnyDaCapo()) { DaCapoImmune = DamageType.None; CurrentPlayingMusic = MusicType.None; } }
public void PlayForest() { currentBGM = MusicType.forrest; audio.Stop(); audio.clip = forestBgm; audio.loop = true; audio.Play(); }
public void PlayMusic(MusicType musicType) { if (transitionCor != null) { StopCoroutine(transitionCor); } transitionCor = StartCoroutine(AudioTransition(musicType)); }
public MusicType FindMusicType(byte musicTypeIdentifier) { MusicType musicType = null; musicType = MusicTypeDao.Find(musicTypeIdentifier); return(musicType); }
public static void Main()//Main_8_4_1 { MusicType mt = MusicType.Jazz; Console.WriteLine(mt.ToString()); Console.WriteLine(mt.ToString("D")); Console.WriteLine(mt.ToString("G")); }
public void ShuffleMusic(float fadeTime, MusicType type) { switch (type) { case MusicType.Start: bgmPlayer.clip = _startBgm; break; case MusicType.Main: bgmPlayer.clip = _mainBgm; break; case MusicType.End: bgmPlayer.clip = _endBgm; break; } bgmPlayer.Play(); StartCoroutine(FadeMusicCoroutine(0f, 1f, fadeTime)); }
/// <summary> /// 构造函数 /// </summary> /// <param name="Title">歌曲标题</param> /// <param name="Url">歌曲路径</param> /// <param name="Like">喜欢次数</param> /// <param name="Listen">收听次数</param> /// <param name="Type">歌曲类型</param> public Music(string Title,string Url,int Like,int Listen,MusicType Type) { //音乐的标题 this.Title = Title; //音乐的路径 this.Url = Url; //音乐被喜欢的次数 this.Like = Like; //音乐被收听的次数 this.Listen = Listen; //音乐的类型 this.Type = Type; }
public void PlaySound(MusicType type) { //AudioClip a = audioSource.clip; //audioSource.Stop(); switch (type) { default: case MusicType.GetWater: audioSource.PlayOneShot(gettingWaterMusic); break; case MusicType.LoseWater: audioSource.PlayOneShot(loseWaterMusic); break; } //audioSource }
public static void PlayMusic(MusicType type) { if (_musicDict[type] != null) { _audio.Stop(); _audio.clip = _musicDict[type]; _audio.loop = true; _audio.volume = 0.25f; if (type == MusicType.GameDrums) { _audio.volume = 0.55f; } _audio.spatialBlend = 0; _audio.Play(); } else { Debug.Log("The MusicType " + type + " is null"); } }
public void PlaySong(MusicType type) { audioSource.Stop(); switch (type) { default: case MusicType.Title: audioSource.clip = titleMusic; break; case MusicType.WayDown: audioSource.clip = backgroundMusicDown; break; case MusicType.WayUp: audioSource.clip = backgroundMusicUp; break; } audioSource.Play(); }
public void UsrFavoursParentMusicType_BannerTargetsChild_BannerIsServed() { Usr u = new Usr(); u.Name = Guid.NewGuid().ToString(); u.Update(); MusicType parentMusicType = new MusicType() { ParentK = 1 }; parentMusicType.Update(); MusicType childMusicType = new MusicType() { ParentK = parentMusicType.K }; childMusicType.Update(); UsrMusicTypeFavourite umtf = new UsrMusicTypeFavourite() { MusicTypeK = parentMusicType.K, UsrK = u.K }; umtf.Update(); Banner b = new Banner() { IsMusicTargetted = true }; b.Update(); b.SaveMusicTargetting(new List<int>() { childMusicType.K }); MusicTypesFavouredByIdentityRule rule = new MusicTypesFavouredByIdentityRule(new UsrIdentity(u)); RequestRules rr = new RequestRules(); rr.MusicTypes = rule; ReadOnlyCollection<BannerDataHolder> results = rr.GetBannersSatsfyingQueryConditionsInTimeslot(Timeslots.GetCurrentTimeslot()); Assert.IsTrue(ContainsBanner(b.K, results)); }
private static SoundState CheckState(MusicType type) { return MusicList[type].State; }
/// <summary> /// 添加音乐 /// </summary> /// <param name="Title">标题</param> /// <param name="Url">地址</param> /// <param name="Type">类型</param> public void AddMusic(string Title,string Url,MusicType Type) { XElement Xe = XElement.Load(XmlFilePath); XElement Music = new XElement("Music", new XElement("Title",Title), new XElement("Url",Url), new XElement("Like",0), new XElement("Listen",0), new XElement("Type",GetValueByType(Type))); Xe.Add(Music); Xe.Save(XmlFilePath); }
private static void PlayMusic(MusicType type, bool restart = true) { if (ActiveMusic == type && CheckState(type) == SoundState.Playing) return; LastMusic = ActiveMusic; ActiveMusic = type; PauseAllMusic(); if (restart) MusicList[type].Stop(); MusicList[type].Play(); }
public static async Task QueueSong(IGuildUser queuer, ITextChannel textCh, IVoiceChannel voiceCh, string query, bool silent = false, MusicType musicType = MusicType.Normal) { if (voiceCh == null || voiceCh.Guild != textCh.Guild) { if (!silent) await textCh.SendMessageAsync("💢 You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining.").ConfigureAwait(false); throw new ArgumentNullException(nameof(voiceCh)); } if (string.IsNullOrWhiteSpace(query) || query.Length < 3) throw new ArgumentException("💢 Invalid query for queue song.", nameof(query)); var musicPlayer = MusicPlayers.GetOrAdd(textCh.Guild.Id, server => { float vol = 1;// SpecificConfigurations.Default.Of(server.Id).DefaultMusicVolume; using (var uow = DbHandler.UnitOfWork()) { vol = uow.GuildConfigs.For(textCh.Guild.Id).DefaultMusicVolume; } var mp = new MusicPlayer(voiceCh, vol); IUserMessage playingMessage = null; IUserMessage lastFinishedMessage = null; mp.OnCompleted += async (s, song) => { if (song.PrintStatusMessage) { try { if (lastFinishedMessage != null) await lastFinishedMessage.DeleteAsync().ConfigureAwait(false); if (playingMessage != null) await playingMessage.DeleteAsync().ConfigureAwait(false); try { lastFinishedMessage = await textCh.SendMessageAsync($"🎵`Finished`{song.PrettyName}").ConfigureAwait(false); } catch { } if (mp.Autoplay && mp.Playlist.Count == 0 && song.SongInfo.Provider == "YouTube") { await QueueSong(queuer.Guild.GetCurrentUser(), textCh, voiceCh, (await NadekoBot.Google.GetRelatedVideosAsync(song.SongInfo.Query, 4)).ToList().Shuffle().FirstOrDefault(), silent, musicType).ConfigureAwait(false); } } catch { } } }; mp.OnStarted += async (s, song) => { if (song.PrintStatusMessage) { var sender = s as MusicPlayer; if (sender == null) return; var msgTxt = $"🎵`Playing`{song.PrettyName} `Vol: {(int)(sender.Volume * 100)}%`"; try { playingMessage = await textCh.SendMessageAsync(msgTxt).ConfigureAwait(false); } catch { } } }; return mp; }); Song resolvedSong; try { musicPlayer.ThrowIfQueueFull(); resolvedSong = await Song.ResolveSong(query, musicType).ConfigureAwait(false); if (resolvedSong == null) throw new SongNotFoundException(); musicPlayer.AddSong(resolvedSong, queuer.Username); } catch (PlaylistFullException) { try { await textCh.SendMessageAsync($"🎵 `Queue is full at {musicPlayer.MaxQueueSize}/{musicPlayer.MaxQueueSize}.` "); } catch { } throw; } if (!silent) { try { var queuedMessage = await textCh.SendMessageAsync($"🎵`Queued`{resolvedSong.PrettyName} **at** `#{musicPlayer.Playlist.Count + 1}`").ConfigureAwait(false); var t = Task.Run(async () => { try { await Task.Delay(10000).ConfigureAwait(false); await queuedMessage.DeleteAsync().ConfigureAwait(false); } catch { } }).ConfigureAwait(false); } catch { } // if queued message sending fails, don't attempt to delete it } }
private string GetValueByType(MusicType Type) { string Value = string.Empty; switch (Type) { case MusicType.Local: Value = "Local"; break; case MusicType.Web: Value = "Web"; break; } return Value; }
private static void RegisterMusic(ContentManager content, MusicType type, string fileName, bool loop) { var instance = content.Load<SoundEffect>(AudioDirectory + fileName).CreateInstance(); instance.IsLooped = loop; MusicList.Add(type, instance); }
public void PlayMusic(MusicType musicType) { PlayMusic((int)musicType); }
public static async Task<Song> ResolveSong(string query, MusicType musicType = MusicType.Normal) { if (string.IsNullOrWhiteSpace(query)) throw new ArgumentNullException(nameof(query)); if (musicType != MusicType.Local && IsRadioLink(query)) { musicType = MusicType.Radio; query = await HandleStreamContainers(query).ConfigureAwait(false) ?? query; } try { switch (musicType) { case MusicType.Local: return new Song(new SongInfo { Uri = "\"" + Path.GetFullPath(query) + "\"", Title = Path.GetFileNameWithoutExtension(query), Provider = "Local File", ProviderType = musicType, Query = query, }); case MusicType.Radio: return new Song(new SongInfo { Uri = query, Title = $"{query}", Provider = "Radio Stream", ProviderType = musicType, Query = query }) { TotalLength = TimeSpan.MaxValue }; } if (SoundCloud.Default.IsSoundCloudLink(query)) { var svideo = await SoundCloud.Default.ResolveVideoAsync(query).ConfigureAwait(false); return new Song(new SongInfo { Title = svideo.FullName, Provider = "SoundCloud", Uri = svideo.StreamLink, ProviderType = musicType, Query = svideo.TrackLink, }) { TotalLength = TimeSpan.FromMilliseconds(svideo.Duration) }; } if (musicType == MusicType.Soundcloud) { var svideo = await SoundCloud.Default.GetVideoByQueryAsync(query).ConfigureAwait(false); return new Song(new SongInfo { Title = svideo.FullName, Provider = "SoundCloud", Uri = svideo.StreamLink, ProviderType = MusicType.Normal, Query = svideo.TrackLink, }) { TotalLength = TimeSpan.FromMilliseconds(svideo.Duration) }; } var link = (await NadekoBot.Google.GetVideosByKeywordsAsync(query).ConfigureAwait(false)).FirstOrDefault(); if (string.IsNullOrWhiteSpace(link)) throw new OperationCanceledException("Not a valid youtube query."); var allVideos = await Task.Run(async () => { try { return await YouTube.Default.GetAllVideosAsync(link).ConfigureAwait(false); } catch { return Enumerable.Empty<YouTubeVideo>(); } }).ConfigureAwait(false); var videos = allVideos.Where(v => v.AdaptiveKind == AdaptiveKind.Audio); var video = videos .Where(v => v.AudioBitrate < 256) .OrderByDescending(v => v.AudioBitrate) .FirstOrDefault(); if (video == null) // do something with this error throw new Exception("Could not load any video elements based on the query."); var m = Regex.Match(query, @"\?t=(?<t>\d*)"); int gotoTime = 0; if (m.Captures.Count > 0) int.TryParse(m.Groups["t"].ToString(), out gotoTime); var song = new Song(new SongInfo { Title = video.Title.Substring(0, video.Title.Length - 10), // removing trailing "- You Tube" Provider = "YouTube", Uri = video.Uri, Query = link, ProviderType = musicType, }); song.SkipTo = gotoTime; return song; } catch (Exception ex) { Console.WriteLine($"Failed resolving the link.{ex.Message}"); return null; } }
public static async Task<Song> ResolveSong(string query, MusicType musicType = MusicType.Normal) { if (string.IsNullOrWhiteSpace(query)) throw new ArgumentNullException(nameof(query)); if (musicType != MusicType.Local && IsRadioLink(query)) { musicType = MusicType.Radio; query = await HandleStreamContainers(query) ?? query; } try { switch (musicType) { case MusicType.Local: return new Song(new SongInfo { Uri = "\"" + Path.GetFullPath(query) + "\"", Title = Path.GetFileNameWithoutExtension(query), Provider = "Local File", ProviderType = musicType, Query = query, }); case MusicType.Radio: return new Song(new SongInfo { Uri = query, Title = $"{query}", Provider = "Radio Stream", ProviderType = musicType, Query = query }); } if (SoundCloud.Default.IsSoundCloudLink(query)) { var svideo = await SoundCloud.Default.GetVideoAsync(query); return new Song(new SongInfo { Title = svideo.FullName, Provider = "SoundCloud", Uri = svideo.StreamLink, ProviderType = musicType, Query = query, }); } var link = await SearchHelper.FindYoutubeUrlByKeywords(query); if (link == String.Empty) throw new OperationCanceledException("Not a valid youtube query."); var allVideos = await Task.Factory.StartNew(async () => await YouTube.Default.GetAllVideosAsync(link)).Unwrap(); var videos = allVideos.Where(v => v.AdaptiveKind == AdaptiveKind.Audio); var video = videos .Where(v => v.AudioBitrate < 192) .OrderByDescending(v => v.AudioBitrate) .FirstOrDefault(); if (video == null) // do something with this error throw new Exception("Could not load any video elements based on the query."); return new Song(new SongInfo { Title = video.Title.Substring(0, video.Title.Length - 10), // removing trailing "- You Tube" Provider = "YouTube", Uri = video.Uri, Query = link, ProviderType = musicType, }); } catch (Exception ex) { Console.WriteLine($"Failed resolving the link.{ex.Message}"); return null; } }
private async Task QueueSong(Channel textCh, Channel voiceCh, string query, bool silent = false, MusicType musicType = MusicType.Normal) { if (voiceCh == null || voiceCh.Server != textCh.Server) { if (!silent) await textCh.SendMessage("💢 You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining."); throw new ArgumentNullException(nameof(voiceCh)); } if (string.IsNullOrWhiteSpace(query) || query.Length < 3) throw new ArgumentException("💢 Invalid query for queue song.", nameof(query)); var musicPlayer = MusicPlayers.GetOrAdd(textCh.Server, server => { float? vol = null; float throwAway; if (DefaultMusicVolumes.TryGetValue(server.Id, out throwAway)) vol = throwAway; var mp = new MusicPlayer(voiceCh, vol); Message playingMessage = null; Message lastFinishedMessage = null; mp.OnCompleted += async (s, song) => { if (song.PrintStatusMessage) { try { if (lastFinishedMessage != null) await lastFinishedMessage.Delete(); if (playingMessage != null) await playingMessage.Delete(); lastFinishedMessage = await textCh.SendMessage($"🎵`Finished`{song.PrettyName}"); } catch { } } }; mp.OnStarted += async (s, song) => { if (song.PrintStatusMessage) { var sender = s as MusicPlayer; if (sender == null) return; try { var msgTxt = $"🎵`Playing`{song.PrettyName} `Vol: {(int)(sender.Volume * 100)}%`"; playingMessage = await textCh.SendMessage(msgTxt); } catch { } } }; return mp; }); var resolvedSong = await Song.ResolveSong(query, musicType); resolvedSong.MusicPlayer = musicPlayer; musicPlayer.AddSong(resolvedSong); if (!silent) { var queuedMessage = await textCh.SendMessage($"🎵`Queued`{resolvedSong.PrettyName} **at** `#{musicPlayer.Playlist.Count}`"); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed Task.Run(async () => { await Task.Delay(10000); try { await queuedMessage.Delete(); } catch { } }); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed } }
public static async Task QueueSong(User queuer, Channel textCh, Channel voiceCh, string query, bool silent = false, MusicType musicType = MusicType.Normal) { if (voiceCh == null || voiceCh.Server != textCh.Server) { if (!silent) await textCh.SendMessage("💢 You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining.").ConfigureAwait(false); throw new ArgumentNullException(nameof(voiceCh)); } if (string.IsNullOrWhiteSpace(query) || query.Length < 3) throw new ArgumentException("💢 Invalid query for queue song.", nameof(query)); var musicPlayer = MusicPlayers.GetOrAdd(textCh.Server, server => { float vol = SpecificConfigurations.Default.Of(server.Id).DefaultMusicVolume; var mp = new MusicPlayer(voiceCh, vol); Message playingMessage = null; Message lastFinishedMessage = null; mp.OnCompleted += async (s, song) => { if (song.PrintStatusMessage) { try { if (lastFinishedMessage != null) await lastFinishedMessage.Delete().ConfigureAwait(false); if (playingMessage != null) await playingMessage.Delete().ConfigureAwait(false); lastFinishedMessage = await textCh.SendMessage($"🎵`Finished`{song.PrettyName}").ConfigureAwait(false); if (mp.Autoplay && mp.Playlist.Count == 0 && song.SongInfo.Provider == "YouTube") { await QueueSong(queuer.Server.CurrentUser, textCh, voiceCh, (await SearchHelper.GetRelatedVideoIds(song.SongInfo.Query, 4)).ToList().Shuffle().FirstOrDefault(), silent, musicType).ConfigureAwait(false); } } catch (Exception e) { Console.WriteLine(e); } } }; mp.OnStarted += async (s, song) => { if (song.PrintStatusMessage) { var sender = s as MusicPlayer; if (sender == null) return; try { var msgTxt = $"🎵`Playing`{song.PrettyName} `Vol: {(int)(sender.Volume * 100)}%`"; playingMessage = await textCh.SendMessage(msgTxt).ConfigureAwait(false); } catch { } } }; return mp; }); Song resolvedSong; try { musicPlayer.ThrowIfQueueFull(); resolvedSong = await Song.ResolveSong(query, musicType).ConfigureAwait(false); musicPlayer.AddSong(resolvedSong, queuer.Name); } catch (PlaylistFullException) { await textCh.SendMessage($"🎵 `Queue is full at {musicPlayer.MaxQueueSize}/{musicPlayer.MaxQueueSize}.` "); throw; } if (!silent) { var queuedMessage = await textCh.SendMessage($"🎵`Queued`{resolvedSong.PrettyName} **at** `#{musicPlayer.Playlist.Count + 1}`").ConfigureAwait(false); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed Task.Run(async () => { await Task.Delay(10000).ConfigureAwait(false); try { await queuedMessage.Delete().ConfigureAwait(false); } catch { } }).ConfigureAwait(false); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed } }
public void UsrFavoursOneMusicType_BannerTargetsAnother_BannerIsNotServed() { Usr u = new Usr(); u.Name = Guid.NewGuid().ToString(); u.Update(); MusicType musicTypeA = new MusicType() { ParentK = 1 }; musicTypeA.Update(); MusicType musicTypeB = new MusicType() { ParentK = 1 }; musicTypeB.Update(); UsrMusicTypeFavourite umtf = new UsrMusicTypeFavourite() { MusicTypeK = musicTypeA.K, UsrK = u.K }; umtf.Update(); Banner b = new Banner() { IsMusicTargetted = true }; b.Update(); BannerMusicType bmt = new BannerMusicType() { BannerK = b.K, MusicTypeK = musicTypeB.K }; bmt.Update(); MusicTypesFavouredByIdentityRule rule = new MusicTypesFavouredByIdentityRule(new UsrIdentity(u)); RequestRules rr = new RequestRules() { MusicTypes = rule }; ReadOnlyCollection<BannerDataHolder> results = rr.GetBannersSatsfyingQueryConditionsInTimeslot(Timeslots.GetCurrentTimeslot()); Assert.IsFalse(ContainsBanner(b.K, results)); }
public static async Task<Song> ResolveSong(string query, MusicType musicType = MusicType.Normal) { if (string.IsNullOrWhiteSpace(query)) throw new ArgumentNullException(nameof(query)); if (musicType != MusicType.Local && IsRadioLink(query)) { musicType = MusicType.Radio; query = await HandleStreamContainers(query).ConfigureAwait(false) ?? query; } try { switch (musicType) { case MusicType.Local: return new Song(new SongInfo { Uri = "\"" + Path.GetFullPath(query) + "\"", Title = Path.GetFileNameWithoutExtension(query), Provider = "Local File", ProviderType = musicType, Query = query, }); case MusicType.Radio: return new Song(new SongInfo { Uri = query, Title = $"{query}", Provider = "Radio Stream", ProviderType = musicType, Query = query }); } if (SoundCloud.Default.IsSoundCloudLink(query)) { var svideo = await SoundCloud.Default.ResolveVideoAsync(query).ConfigureAwait(false); return new Song(new SongInfo { Title = svideo.FullName, Provider = "SoundCloud", Uri = svideo.StreamLink, ProviderType = musicType, Query = svideo.TrackLink, }); } if (musicType == MusicType.Soundcloud) { var svideo = await SoundCloud.Default.GetVideoByQueryAsync(query).ConfigureAwait(false); return new Song(new SongInfo { Title = svideo.FullName, Provider = "SoundCloud", Uri = svideo.StreamLink, ProviderType = MusicType.Normal, Query = svideo.TrackLink, }); } var link = await SearchHelper.FindYoutubeUrlByKeywords(query).ConfigureAwait(false); if (string.IsNullOrWhiteSpace(link)) throw new OperationCanceledException("Not a valid youtube query."); var allVideos = await Task.Factory.StartNew(async () => await YouTube.Default.GetAllVideosAsync(link).ConfigureAwait(false)).Unwrap().ConfigureAwait(false); var videos = allVideos.Where(v => v.AdaptiveKind == AdaptiveKind.Audio); var video = videos .Where(v => v.AudioBitrate < 192) .OrderByDescending(v => v.AudioBitrate) .FirstOrDefault(); if (video == null) // do something with this error throw new Exception("Could not load any video elements based on the query."); var m = Regex.Match(query, @"\?t=((?<h>\d*)h)?((?<m>\d*)m)?((?<s>\d*)s?)?"); int gotoTime = 0; if (m.Captures.Count > 0) { int hours; int minutes; int seconds; int.TryParse(m.Groups["h"].ToString(), out hours); int.TryParse(m.Groups["m"].ToString(), out minutes); int.TryParse(m.Groups["s"].ToString(), out seconds); gotoTime = hours * 60 * 60 + minutes * 60 + seconds; } var song = new Song(new SongInfo { Title = video.Title.Substring(0, video.Title.Length - 10), // removing trailing "- You Tube" Provider = "YouTube", Uri = video.Uri, Query = link, ProviderType = musicType, }); song.SkipTo = gotoTime; return song; } catch (Exception ex) { Console.WriteLine($"Failed resolving the link.{ex.Message}"); return null; } }