Ejemplo n.º 1
0
 private void _musicManagerMediaLoaded(MusicModel model)
 {
     SynchronizationContext.Post((o) =>
     {
         IsLoading = false;
     }, null);
 }
Ejemplo n.º 2
0
        public async Task <MediaPlaybackItem> Add(MusicModel model)
        {
            var indexInPlaybackList = _getIndex(model);

            // Prepare audio steam
            var source = await musicService.GetCahchedMusicAsync(model);

            if (source == null)
            {
                try
                {
                    source = await musicService.RequestMusic(model);
                }
                catch (Exception e)
                {
                    _logger.Error($"Get music stream failed", e);
                }
            }

            var playbackItem = _createMediaPlaybackItem(source, model);

            if (indexInPlaybackList != null)
            {
                _mediaPlaybackList.Items[indexInPlaybackList.Value] = playbackItem;
            }
            else
            {
                _mediaPlaybackList.Items.Add(playbackItem);
            }
            return(playbackItem);
        }
Ejemplo n.º 3
0
 public String Actualizar(String nombreGenero)
 {
     try
     {
         MusicModel   modelo  = new MusicModel();
         SqlParameter idParam = new SqlParameter
         {
             ParameterName = "@nombreGenero",
             Value         = nombreGenero
         };
         modelo.Database.SqlQuery <List <string> >("exec Spr_InsertarGenero @nombreGenero", idParam).ToList();
         return("OK");
     }
     catch (SqlException sqlExcepcion)
     {
         /* if(sqlExcepcion.ErrorCode == 21) {
          *   return "Eror de conexion";
          * }else if*/
         return("Error en Base de datos: " + sqlExcepcion.Message);
     }
     catch (Exception ex)
     {
         return("Error general: " + ex.Message);
     }
 }
Ejemplo n.º 4
0
        private async Task <IStorageFile> _createMusicFile(MusicModel model)
        {
            StorageFolder folder = null;

            try
            {
                folder = await ApplicationData.Current.LocalFolder.GetFolderAsync(Definition.LOCALSTATE_CACHEDMUSIC);
            }
            catch (FileNotFoundException)
            {
                _logger.Warning($"Get music' cache folder failed");
            }

            if (folder == null)
            {
                folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(Definition.LOCALSTATE_CACHEDMUSIC);
            }

            StorageFile cacheFile = null;

            try
            {
                cacheFile = await folder.CreateFileAsync(_utilityHelper.CreateMd5HashString(model.Title), CreationCollisionOption.FailIfExists);
            }
            catch (Exception e)
            {
                _logger.Error($"Create music' cache file failed", e);
            }
            return(cacheFile);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Get music stream from the local cache
        /// </summary>
        public async Task <MediaSource> GetCahchedMusicAsync(MusicModel model)
        {
            StorageFolder folder = null;

            try
            {
                folder = await ApplicationData.Current.LocalFolder.GetFolderAsync("CachedMusic");
            }
            catch (FileNotFoundException)
            {
                _logger.Warning($"Get music's cache folder failed");
                return(null);
            }

            try
            {
                var hashName   = _utilityHelper.CreateMd5HashString(model.Title);
                var cachedFile = await folder.GetFileAsync(hashName);

                var ras = await cachedFile.OpenAsync(FileAccessMode.Read);

                _logger.Debug($"Music {model.Title}({hashName}) has local cache");
                return(MediaSource.CreateFromStream(ras, "audio/mpeg"));
            }
            catch
            {
                _logger.Warning($"Get cached music file failed, target music info:{Environment.NewLine}" +
                                $"\tTitle: {model.Title}{Environment.NewLine}" +
                                $"\tUrl: {model.Uri}");
                return(null);
            }
        }
 public IActionResult UpdateBasic(UpdateBasicMusicViewModel model)
 {
     if (int.TryParse(model.SingerId, out int singerId) &&
         int.TryParse(model.AlbumId, out int albumId))
     {
         var music = new MusicModel()
         {
             Id       = model.Id,
             Name     = model.Name,
             SingerId = singerId,
             AlbumId  = albumId,
             MenderId = HttpContext.Session.GetCurrentUserId()
         };
         music = _musicAppService.UpdateBasic(music);
         return(Json(new JsonResultEntity()
         {
             Message = "更新基本信息成功!",
             JsonObject = Json(new MusicViewModel()
             {
                 Id = music.Id,
                 SingerId = music.SingerId,
                 AlbumId = music.AlbumId,
                 MenderId = music.MenderId,
                 Name = music.Name,
                 SingerName = music.SingerName,
                 AlbumName = music.AlbumName,
                 MenderName = music.MenderName,
                 LastModificationTime = music.LastModificationTime?.ToStandardDateOfChina()
             })
         }));
     }
     throw new JMBasicException("歌唱家或专辑不存在");
 }
Ejemplo n.º 7
0
        //Realiza o update da música nas listas cache ou no banco
        public ActionResult UpdateConfirmedMusic(MusicModel musicView)
        {
            int idMusicUpdate      = Convert.ToInt32(TempData["IdMusicUpdate"]);
            var idAlbumUpdateMusic = musicView.IdAlbum;
            var indicatorFlag      = TempData["IndicatorFlag"];


            if (idAlbumUpdateMusic == 0)
            {
                listMusicAdd.RemoveAt(idMusicUpdate - 1);
                listMusicAdd.Insert(idMusicUpdate - 1, musicView);
            }
            else
            {
                if (indicatorFlag.Equals("new"))
                {
                    listMusicUpdate.RemoveAt(idMusicUpdate - 1);
                    listMusicUpdate.Insert(idMusicUpdate - 1, musicView);
                }
                else
                {
                    var music = Mapper.Map <MusicModel, MusicVO>(musicView);
                    music.Id = idMusicUpdate;
                    musicBusiness.Update(music);
                }
            }

            return(RedirectToAction("UpdateAlbum", new { id = idAlbumUpdateMusic }));
        }
Ejemplo n.º 8
0
        //Confirma a exclusão da música
        public ActionResult DeleteConfirmedMusic(MusicModel musicView)
        {
            int idMusicDeleteMusic = Convert.ToInt32(TempData["idMusicDeleteMusic"]);
            var typedText          = Request["Delete"].ToString().ToLower();
            var idAlbumDeleteMusic = musicView.IdAlbum;
            var indicatorFlag      = TempData["indicatorFlag"];

            //Verifica se foi digitado excluir no campo de texto
            if ("excluir".Equals(typedText))
            {
                //se o ID do álbum for 0, está excluindo a música de um novo álbum, senão a exclusão é durante a edição de um álbum já existente
                if (idAlbumDeleteMusic == 0)
                {
                    //remove a música da lista de cache de álbum novo
                    listMusicAdd.RemoveAt(idMusicDeleteMusic - 1);
                }
                else
                {
                    //verifica se o flag de indicação da música é nova música(id da música é um contador) ou se é uma música do banco(idMusic)
                    if (indicatorFlag.Equals("new"))
                    {
                        //remove a música da lista de cache de um álbum antigo
                        listMusicUpdate.RemoveAt(idMusicDeleteMusic - 1);
                    }
                    else
                    {
                        //remove a música do banco
                        musicBusiness.Delete(idMusicDeleteMusic);
                    }
                }
            }

            return(RedirectToAction("UpdateAlbum", new { id = idAlbumDeleteMusic }));
        }
Ejemplo n.º 9
0
        //Abre o PartialView de UpdateMusic
        public ActionResult ShowUpdateMusic(int idMusic, int idAlbum, string indicatorFlag)
        {
            TempData["IdMusicUpdate"] = idMusic;
            TempData["IndicatorFlag"] = indicatorFlag;

            var musicModel = new MusicModel();

            if (idAlbum == 0)
            {
                musicModel = listMusicAdd[idMusic - 1];
            }
            else
            {
                if (indicatorFlag.Equals("new"))
                {
                    musicModel = listMusicUpdate[idMusic - 1];
                }
                else
                {
                    var music = musicBusiness.GetForId(idMusic);
                    musicModel = Mapper.Map <MusicVO, MusicModel>(music);
                }
            }

            return(PartialView("_UpdateMusic", musicModel));
        }
Ejemplo n.º 10
0
        public static async Task <IActionResult> CreateSong(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "music/song")] HttpRequest req,
            [CosmosDB(
                 databaseName: "musicDatabase",
                 collectionName: "albumContainer",
                 ConnectionStringSetting = "databaseConnection")] DocumentClient client,
            ILogger log)
        {
            Uri collectionUri = UriFactory.CreateDocumentCollectionUri("albumDatabase", "albumContainer");

            MusicModel musicModel = new MusicModel();

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            musicModel.Id         = Guid.NewGuid().ToString();
            musicModel.Singer     = data?.singer;
            musicModel.Album      = data?.album;
            musicModel.Song       = data?.song;
            musicModel.Genre      = data?.genre;
            musicModel.Release    = data?.release;
            musicModel.CreateDate = DateTime.Now;

            await client.CreateDocumentAsync(collectionUri, musicModel);

            return(new OkObjectResult(musicModel));
        }
Ejemplo n.º 11
0
 private void _musicManagerMediaEnd(MusicModel model)
 {
     SynchronizationContext.Post((o) =>
     {
         NextClicked();
     }, null);
 }
Ejemplo n.º 12
0
        public ActionResult Details(int id)
        {
            MusicModel song = new MusicModel();

            song = SqliteConnector.LoadSongDetails(id).SingleOrDefault(x => x.Id == id);

            return(View(song));
        }
Ejemplo n.º 13
0
 private async Task <MediaPlaybackItem> _cacheMusic(MusicModel model)
 {
     if (!CachedMusicList.Any(m => m.Title == model.Title))
     {
         CachedMusicList.Add(model);
     }
     return(await Add(model));
 }
Ejemplo n.º 14
0
        //*******Partial Views********//

        //Abre o PartialView de Inserção/Alteração e pega o id do álbum
        public ActionResult ShowInsertMusic(int id)
        {
            var musicModel = new MusicModel()
            {
                IdAlbum = id
            };

            return(PartialView("_InsertMusic", musicModel));
        }
Ejemplo n.º 15
0
        public static async Task <HttpResponseMessage> GetSong(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "music/song")] HttpRequest req,
            [CosmosDB(
                 databaseName: "musicDatabase",
                 collectionName: "albumContainer",
                 ConnectionStringSetting = "databaseConnection")] DocumentClient client,
            ILogger log)
        {
            var ids = req.Query["id"];

            if (string.IsNullOrWhiteSpace(ids))
            {
                return(HttpResponseMessage(HttpStatusCode.NotFound));
            }

            Uri collectionUri = UriFactory.CreateDocumentCollectionUri("albumDatabase", "albumContainer");

            var options = new FeedOptions {
                EnableCrossPartitionQuery = true
            };

            IDocumentQuery <MusicModel> query = client.CreateDocumentQuery <MusicModel>(collectionUri, options)
                                                .Where(p => p.Id.Contains(ids))
                                                .AsDocumentQuery();

            MusicModel musicModel = new MusicModel();

            while (query.HasMoreResults)
            {
                foreach (MusicModel result in await query.ExecuteNextAsync())
                {
                    musicModel.Id         = result.Id;
                    musicModel.Singer     = result.Singer;
                    musicModel.Album      = result.Album;
                    musicModel.Song       = result.Song;
                    musicModel.Genre      = result.Genre;
                    musicModel.Release    = result.Release;
                    musicModel.CreateDate = result.CreateDate;
                }
            }

            try
            {
                var json = JsonConvert.SerializeObject(musicModel, Formatting.Indented);
                return(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(json, Encoding.UTF8, "application/json")
                });
            }
            catch (Exception e)
            {
                log.LogError($"Error Result:{e.Message}");
                return(new HttpResponseMessage(HttpStatusCode.NotFound));
            }
        }
Ejemplo n.º 16
0
 public RadioStation(string name)
 {
     audianceList = new List <Audiance>();
     id           = id_seq++;
     balance      = 1500;
     this.name    = name;
     music        = new MusicModel(Artists.allArtists[0].artistSongs[0]);
     SoundQUality = 30;
     SoundRange   = 30;
     ArtistBougth = new List <Artists>();
 }
Ejemplo n.º 17
0
        public MusicModel CreateSong(MusicModel model)
        {
            using (IDbConnection cnn = new SQLiteConnection(GlobalConfig.CnnString(GlobalConfig.db)))
            {
                cnn.Execute("Insert into Music Name, Artist, Year, Alblum, CoverArt, Rank) values (@Name, @Artist, @Year, @Alblum, @CoverArt, @ Rank) ", model);

                //TODO: Get new ID

                return(model);
            }
        }
Ejemplo n.º 18
0
 public async Task Play(MusicModel model)
 {
     if (_isPaused)
     {
         _mediaPlayer.Play();
     }
     else
     {
         await _play(model);
     }
 }
Ejemplo n.º 19
0
        private void _mediaPlaybackListItemFailed(MediaPlaybackList sender, MediaPlaybackItemFailedEventArgs args)
        {
            MusicModel model = null;

            if (args.Item.Source.CustomProperties.TryGetValue("model", out object value))
            {
                var modelJson = value as string;
                model = JsonSerializer.Deserialize <MusicModel>(modelJson);
                _logger.Error($"Play music failed: \n\t{modelJson}\n\t{args.Error.ErrorCode}", args.Error.ExtendedError);
            }
            MediaFailed?.Invoke(model);
        }
Ejemplo n.º 20
0
 public ActionResult register([FromBody] MusicModel Song)
 {
     try
     {
         this.musicServices.Add(Song);
         return(Ok());
     }
     catch (Exception ex)
     {
         return(BadRequest(ex.Message));
     }
 }
Ejemplo n.º 21
0
        private MediaPlaybackItem _createMediaPlaybackItem(MediaSource source, MusicModel model)
        {
            source.CustomProperties["model"] = JsonSerializer.Serialize(model);
            var item = new MediaPlaybackItem(source);
            //Set STMC
            var props = item.GetDisplayProperties();

            props.Type = MediaPlaybackType.Music;
            props.MusicProperties.Title = model.Title;
            item.ApplyDisplayProperties(props);
            return(item);
        }
Ejemplo n.º 22
0
 public void Add(MusicModel Song)
 {
     try {
         CloudTable     table    = verification();
         var            Music    = new MusicModel(Song.Songname, Song.Artist);
         TableOperation insertOp = TableOperation.Insert(Music);
         table.ExecuteAsync(insertOp);
     }
     catch (Exception ex)
     {
         Console.Write(ex);
     }
 }
Ejemplo n.º 23
0
        public ActionResult Edit(int id)
        {
            MusicModel model = new MusicModel();

            var modelMusic = musicRepository.GetById(id);

            model.Song_Id   = modelMusic.Song_Id;
            model.Name_Song = modelMusic.Name_Song;
            model.Singer    = modelMusic.Singer;
            model.Time      = modelMusic.Time;

            return(View("EditMusic", model));
        }
Ejemplo n.º 24
0
 public HttpResponseMessage getByCategory([FromBody] MusicModel music, int tops)
 {
     try
     {
         string[] category             = music.Prime_genre.Split(',');
         IEnumerable <MusicModel> list = listMusic.Where(c => category.Contains(c.Prime_genre)).OrderByDescending(c => c.Rating_count_tot).Take(tops);
         return(ResponseApi(HttpStatusCode.OK, "application/json", null, convertToJson(list), null, null));
     }
     catch (Exception e)
     {
         return(ResponseApi(HttpStatusCode.BadRequest, "application/json", null, convertToJson(errorHandler(e, HttpStatusCode.BadRequest)), null, null));
     }
 }
Ejemplo n.º 25
0
        //Abre o PartialView de exclusão e pega o id do álbum
        public ActionResult ShowDeleteMusic(int idMusic, int idAlbum, string indicatorFlag)
        {
            TempData["IdMusicDeleteMusic"] = idMusic;
            TempData["indicatorFlag"]      = indicatorFlag;
            TempData["IdAlbumDeleteMusic"] = idAlbum;

            var musicModel = new MusicModel()
            {
                IdAlbum = idAlbum,
                Id      = idMusic,
            };

            return(PartialView("_DeleteMusic", musicModel));
        }
Ejemplo n.º 26
0
 public ActionResult ListarGeneros()
 {
     try
     {
         MusicModel         genero       = new MusicModel();
         List <Tbl_Generos> nombreGenero = genero.Database.SqlQuery <Tbl_Generos>("Spr_ListarGeneros").ToList();
         //{'idGenero':1, 'genero': 'Rock'}
         return(Json(nombreGenero, JsonRequestBehavior.AllowGet));
     }
     catch (Exception ex)
     {
         return(Json(ex.Message, JsonRequestBehavior.AllowGet));
     }
 }
Ejemplo n.º 27
0
 public ActionResult ListarCanciones()
 {
     try
     {
         MusicModel         modelo          = new MusicModel();
         List <CancionView> nombreCanciones = modelo.Database.SqlQuery <CancionView>("spr_ListarCanciones").ToList();
         //{'idGenero':1, 'genero': 'Rock'}
         return(Json(nombreCanciones, JsonRequestBehavior.AllowGet));
     }
     catch (Exception ex)
     {
         return(Json(ex.Message, JsonRequestBehavior.AllowGet));
     }
 }
Ejemplo n.º 28
0
        private async Task _play(MusicModel model)
        {
            try
            {
                var playbackItem = await _cacheMusic(model);

                var playbackItemIndex = _mediaPlaybackList.Items.IndexOf(playbackItem);
                _mediaPlaybackList.MoveTo((uint)playbackItemIndex);
                _mediaPlayer.Play();
            }
            catch
            {
                MediaFailed?.Invoke(model);
            }
        }
Ejemplo n.º 29
0
        public async Task <IActionResult> OnGetAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            MusicModel = await _context.MusicModel.FirstOrDefaultAsync(m => m.Id == id);

            if (MusicModel == null)
            {
                return(NotFound());
            }
            return(Page());
        }
        public Music UpdateBasic(MusicModel model)
        {
            _userManager.ValidAdminByUserId((int)model.MenderId);
            ValidateForUpdateBasic(model, out Music music);

            music.Name                 = model.Name;
            music.SingerId             = model.SingerId;
            music.AlbumId              = model.AlbumId;
            music.MenderId             = model.MenderId;
            music.LastModificationTime = DateTime.Now;

            Save();

            return(music);
        }
 NoteObject InstantiateNoteObject(MusicModel.NotesData notesData, MusicModel.Note note)
 {
     var noteObject = (Instantiate(noteObjectPrefab) as GameObject).GetComponent<NoteObject>();
     noteObject.notePosition = new NotePosition(notesData.BPM, note.LPB, note.num, note.block);
     noteObject.noteType.Value = note.type == 2 ? NoteTypes.Long : NoteTypes.Normal;
     noteObject.transform.SetParent(notesRegion.transform);
     NotesEditorModel.Instance.NoteObjects.Add(noteObject.notePosition, noteObject);
     return noteObject;
 }
    void InstantiateNotesData(MusicModel.NotesData notesData)
    {
        var editorModel = NotesEditorModel.Instance;

        editorModel.BPM.Value = notesData.BPM;
        editorModel.BeatOffsetSamples.Value = notesData.offset;

        foreach (var note in notesData.notes)
        {
            if (note.type == 1)
            {
                InstantiateNoteObject(notesData, note);
                continue;
            }

            var longNoteObjects = new MusicModel.Note[] { note }.Concat(note.notes)
                .Select(note_ => InstantiateNoteObject(notesData, note_))
                .ToList();

            for (int i = 1; i < longNoteObjects.Count; i++)
            {
                longNoteObjects[i].prev = longNoteObjects[i - 1];
                longNoteObjects[i - 1].next = longNoteObjects[i];
            }
        }
    }