public void Initialize(Stream stream, AudioInfo info, AudioMetadata metadata, SettingDictionary settings) { _stream = stream; _metadata = metadata; _settings = settings; if (info.BitsPerSample == 0) { var logger = LoggerManager.LoggerFactory.CreateLogger <AlacAudioEncoder>(); logger.LogWarning("Transcoding from a lossy to a lossless format."); _bitsPerSample = 16; } else { _bitsPerSample = info.BitsPerSample; } // Pre-allocate the whole stream (estimate worst case compression, plus cover art) stream.SetLength(info.FrameCount * info.Channels * (long)Math.Ceiling(_bitsPerSample / 8.0) + (metadata.CoverArt?.Data.Length ?? 0)); var inputDescription = GetInputDescription(info); _audioFile = new(GetOutputDescription(inputDescription), AudioFileType.M4A, stream); _audioFile.SetProperty(ExtendedAudioFilePropertyId.ClientDataFormat, inputDescription); }
public void ImportPaths(params string[] paths) { if (paths.Any(p => checkExtension(Path.GetExtension(p)))) { return; } foreach (string p in paths) { AudioMetadata meta = new AudioMetadata(); using (var mp3 = new Mp3(p)) { Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2X); if (tag.CustomTexts.Count > 0 && tag.CustomTexts.Any(t => t.Value.StartsWith("DISPLAY ARTIST\0"))) { meta.Artist = meta.ArtistUnicode = tag.CustomTexts.First(t => t.Value.StartsWith("DISPLAY ARTIST\0")).Value.Split("DISPLAY ARTIST\0")[1]; } else if (tag.Artists.Value.Count > 0) { meta.Artist = meta.ArtistUnicode = tag.Artists.Value[0]; } else { meta.Artist = meta.ArtistUnicode = "Unkown Artist"; } meta.Title = meta.TitleUnicode = tag.Title.Value ?? "Unkown Title"; } playlist.AddSong(meta, p); } }
public static bool TryGetAudioMetadata(string songName, out AudioMetadata metadata) { metadata = null; try { string dirPath = GetSongDirectoryPath(songName); if (Directory.Exists(dirPath)) { string filePath = GetAudioMetadataFilePath(songName); if (File.Exists(filePath)) { string jsonStr = File.ReadAllText(filePath, System.Text.Encoding.Unicode); var serialized = JsonUtility.FromJson <SerializableAudioMetadata>(jsonStr); if (serialized != null) { metadata = serialized.GetAsAudioMetadata(); Game.Log(Logging.Category.SONG_DATA, "Read audio metadata from file: " + filePath, Logging.Level.LOG); return(true); } throw new IOException("Audio metadata file is corrupt."); } throw new FileNotFoundException(filePath); } throw new DirectoryNotFoundException(dirPath); } catch (System.Exception e) { Game.Log(Logging.Category.SONG_DATA, "Unable to read audio metadata from file: " + e, Logging.Level.LOG_WARNING); return(false); } }
private IEnumerable <AudioMetadata> GetAudioMetadatas(IEnumerable <int> audioIds, TrackdocDbEntityFramework.trackdocEntities db) { WriteDebugEntry("Initiating retrieval of audio metadata from database."); var audioMetadatas = new List <AudioMetadata>(); //Shakti: Saving 400 ms per record here ..For test 9 records it will take 400 ms compare to 4007 in old code var audioInfos = db.audios .Where(a => audioIds.Contains(a.id)).GroupBy(a => a.id).Select(a => a.FirstOrDefault()) .Select(a => new { Id = a.id, Filename = a.filename, OriginalAudioType = a.audio_type.name.ToLower() }).ToList(); foreach (var audioInfo in audioInfos) { if (audioInfo != null) { var audioMetadata = new AudioMetadata(); audioMetadata.audioId = audioInfo.Id; audioMetadata.TempWorkingFilename = audioInfo.Id.ToString(); audioMetadata.Filename = audioInfo.Filename; audioMetadata.OriginalAudioType = audioInfo.OriginalAudioType; audioMetadata.UnconvertedPath = Path.Combine(tempDirectoryPath, audioInfo.Id + "." + audioMetadata.OriginalAudioType); audioMetadata.IntermediateWavPath = Path.Combine(tempDirectoryPath, audioInfo.Id + ".wav"); audioMetadata.FinalPath = outputPath + audioInfo.Id + ".mp3"; audioMetadatas.Add(audioMetadata); } } WriteDebugEntry("Successfully retrieved metatdata of " + audioMetadatas.Count + " audios from database."); return(audioMetadatas); }
private void ConvertToWav(AudioMetadata audioMetadata) { string converter; DeleteIfExists(audioMetadata.IntermediateWavPath); try { PhilipsConvert(audioMetadata.UnconvertedPath, audioMetadata.IntermediateWavPath); converter = "Philips"; } catch (Exception philipsEx) { var error = "Philips exception:" + Environment.NewLine + philipsEx.ToString(); WriteEventLogEntry("Philips converter could not convert " + audioMetadata.UnconvertedPath + " to " + audioMetadata.IntermediateWavPath + ". Will fallback to Olympus converter. " + error, EventLogEntryType.Warning); try { OlympusConvert(audioMetadata.UnconvertedPath, audioMetadata.IntermediateWavPath); converter = "Olympus"; } catch (Exception olympusEx) { error += Environment.NewLine + Environment.NewLine + "Olympus exception:" + Environment.NewLine + olympusEx.ToString(); throw new Exception("Failure converting " + audioMetadata.UnconvertedPath + " to " + audioMetadata.IntermediateWavPath + Environment.NewLine + Environment.NewLine + error); } } WriteEventLogEntry("Converted " + audioMetadata.UnconvertedPath + " to " + audioMetadata.IntermediateWavPath + " using " + converter + " converter.", EventLogEntryType.Information); }
private void restoreChanges(AudioMetadata newMeta) { Scheduler.Add(() => mainContainer.ScaleTo(1).Then().Delay(30000 - newMeta.Track.CurrentTime + Time.Elapsed).Then().ScaleTo(1).OnComplete(_ => UpdateCover())); exchangeCover.Texture = cover.Texture; cover.Texture = newMeta.Covers.Count == 0 ? null : newMeta.Covers[coverIndex = 0]; if (lastMetadata != null) { subContainer.Show(); mainContainer.MoveToX(1) .Then() .MoveToX(0, 500, Easing.OutQuart) .OnComplete(_ => { exchangeCover.Texture = null; subContainer.Hide(); }); } else { subContainer.Hide(); } lastMetadata = newMeta; }
public static bool TryWriteAudioMetadata(string songName, AudioMetadata metadata) { try { var serialized = new SerializableAudioMetadata(metadata); string jsonStr = JsonUtility.ToJson(serialized); byte[] bytes = System.Text.Encoding.Unicode.GetBytes(jsonStr); string dirPath = GetSongDirectoryPath(songName); string filePath = GetAudioMetadataFilePath(songName); if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite)) { fs.Write(bytes, 0, bytes.Length); } Game.Log(Logging.Category.SONG_DATA, "Wrote audio metadata to file: " + filePath, Logging.Level.LOG); return(true); } catch (System.Exception e) { Game.Log(Logging.Category.SONG_DATA, "Unable to write audio metadata to file: " + e, Logging.Level.LOG_WARNING); } return(false); }
/// <inheritdoc/> public void SaveMetadata(SettingDictionary settings = null) { if (settings == null) { settings = new SettingDictionary(); } var extension = IO.Path.GetExtension(Path); // Make sure the provided settings are clean AudioMetadataEncoderManager.GetSettingInfoByExtension(extension).ValidateSettings(settings); using (var fileStream = File.Open(Path, FileMode.Open)) { // Try each encoder that supports this file extension foreach (var factory in ExtensionProviderWrapper.GetFactories <IAudioMetadataEncoder>( "Extension", extension)) { using (var export = factory.CreateExport()) { if (_metadata == null) { _metadata = LoadMetadata(fileStream); } export.Value.WriteMetadata(fileStream, _metadata, settings); return; } } } throw new AudioUnsupportedException("No supporting extensions are available."); }
public void Initialize(Stream stream, AudioInfo info, AudioMetadata metadata, SettingDictionary settings) { _stream = stream; InitializeReplayGainFilter(info, metadata, settings); // Call the external ID3 encoder, if available var metadataEncoderFactory = ExtensionProvider.GetFactories <IAudioMetadataEncoder>("Extension", FileExtension).FirstOrDefault(); if (metadataEncoderFactory != null) { using (var export = metadataEncoderFactory.CreateExport()) using (var tempStream = new MemoryStream()) { // Buffer the tag in memory export.Value.WriteMetadata(tempStream, metadata, settings); // Pre-allocate the whole stream (estimate worst case of 320kbps, plus the tag) stream.SetLength(0xA000 * (long)info.PlayLength.TotalSeconds + tempStream.Length); // Flush the tag to the output stream tempStream.WriteTo(stream); } } _encoder = new(stream); _encoder.SetChannels(info.Channels); _encoder.SetSampleRate(info.SampleRate); if (info.FrameCount > 0) { _encoder.SetSampleCount((uint)info.FrameCount); } if (settings.TryGetValue("BitRate", out int bitRate)) { // Use ABR, unless ForceCBR is set to true if (settings.TryGetValue("ForceCBR", out bool forceCbr) && forceCbr) { _encoder.SetBitRate(bitRate); } else { _encoder.SetVbrMeanBitRate(bitRate); _encoder.SetVbrMode(VbrMode.Abr); } } else { // Use VBR quality 3 if nothing else is specified _encoder.SetVbrQuality( settings.TryGetValue("VBRQuality", out int vbrQuality) ? vbrQuality : 3); _encoder.SetVbrMode(VbrMode.Mtrh); } _encoder.InitializeParameters(); }
public void Initialize(Stream stream, AudioInfo info, AudioMetadata metadata, SettingDictionary settings) { InitializeReplayGainFilter(info, metadata, settings); _oggStream = new OggStream(settings.TryGetValue("SerialNumber", out int serialNumber) ? serialNumber : new Random().Next()); // Default to a quality setting of 5 if (settings.TryGetValue("BitRate", out int bitRate)) { if (settings.TryGetValue("ForceCBR", out bool cbr) && cbr) { _encoder = new VorbisEncoder(info.Channels, info.SampleRate, bitRate * 1000, bitRate * 1000, bitRate * 1000); } else { _encoder = new VorbisEncoder(info.Channels, info.SampleRate, -1, bitRate * 1000, -1); } } else { _encoder = new VorbisEncoder(info.Channels, info.SampleRate, settings.TryGetValue("Quality", out int quality) ? quality / 10f : 0.5f); } // Generate the header using (var comment = new MetadataToVorbisCommentAdapter(metadata)) { comment.HeaderOut(_encoder.DspState, out var first, out var second, out var third); _oggStream.PacketIn(first); _oggStream.PacketIn(second); _oggStream.PacketIn(third); } // Buffer the header in memory using (var tempStream = new MemoryStream()) { _outputStream = tempStream; // ReSharper disable once PossibleNullReferenceException while (_oggStream.Flush(out var page)) { WritePage(page); } // Pre-allocate the whole stream (estimate worst case of 500kbps, plus the header) stream.SetLength(0xFA00 * (long)info.PlayLength.TotalSeconds + tempStream.Length); // Flush the headers to the output stream tempStream.WriteTo(stream); } _outputStream = stream; }
public SimpleObstacleRythmStyleProcessor(AudioMetadata newAudioMetadata) { audioMetadata = newAudioMetadata; float targetLengthInSec = 3.0f + ((float)rand.NextDouble() * 5.0f); // in seconds float targetLength = targetLengthInSec * (float)audioMetadata.BeatDetectorResult.BeatsPerMinute / 60.0f; // in bpm obstaclePositions = rand.Next(0, 6); if (obstaclePositions == 0) { obstacleA = new Obstacle(); obstacleA.HorizontalPosition = HorizontalPosition.Left; obstacleA.Width = 1; obstacleA.Type = ObstableType.WallFullHeight; } if (obstaclePositions == 1) { obstacleA = new Obstacle(); obstacleA.HorizontalPosition = HorizontalPosition.Left; obstacleA.Width = 2; obstacleA.Type = ObstableType.WallFullHeight; } if (obstaclePositions == 2) { obstacleA = new Obstacle(); obstacleA.HorizontalPosition = HorizontalPosition.Right; obstacleA.Width = 1; obstacleA.Type = ObstableType.WallFullHeight; } if (obstaclePositions == 3) { obstacleA = new Obstacle(); obstacleA.HorizontalPosition = HorizontalPosition.CenterRight; obstacleA.Width = 2; obstacleA.Type = ObstableType.WallFullHeight; } if (obstaclePositions == 4) { obstacleA = new Obstacle(); obstacleA.Type = ObstableType.WallHalfHeight; obstacleA.Width = 4; } if (obstaclePositions == 5) { obstacleA = new Obstacle(); obstacleA.HorizontalPosition = HorizontalPosition.Left; obstacleA.Width = 1; obstacleA.Type = ObstableType.WallFullHeight; obstacleB = new Obstacle(); obstacleB.HorizontalPosition = HorizontalPosition.Right; obstacleB.Width = 1; obstacleB.Type = ObstableType.WallFullHeight; } obstacleA.Duration = targetLength; if (obstacleB != null) { obstacleB.Duration = targetLength; } }
static string GetDateText(AudioMetadata metadata) { if (string.IsNullOrEmpty(metadata.Day) || string.IsNullOrEmpty(metadata.Month)) { return(string.Empty); } return(metadata.Day + metadata.Month); }
public MetadataInfo Copy() { return(new MetadataInfo { AudioMetadata = HasAudio ? AudioMetadata.Copy() : null, VideoMetadata = HasVideo ? VideoMetadata.Copy() : null, DataMetadata = HasData ? DataMetadata.Copy() : null, }); }
static string GetTrackText(AudioMetadata metadata) { if (string.IsNullOrEmpty(metadata.TrackNumber)) { return(string.Empty); } return(string.IsNullOrEmpty(metadata.TrackCount) ? metadata.TrackNumber : $"{metadata.TrackNumber}/{metadata.TrackCount}"); }
internal MetadataToIlstAtomAdapter([NotNull] AudioMetadata metadata, bool compressCoverArt) { if (!string.IsNullOrEmpty(metadata.Title)) { _atoms.Add(new TextAtom("©nam", metadata.Title)); } if (!string.IsNullOrEmpty(metadata.Artist)) { _atoms.Add(new TextAtom("©ART", metadata.Artist)); } if (!string.IsNullOrEmpty(metadata.Album)) { _atoms.Add(new TextAtom("©alb", metadata.Album)); } if (!string.IsNullOrEmpty(metadata.AlbumArtist)) { _atoms.Add(new TextAtom("aART", metadata.AlbumArtist)); } if (!string.IsNullOrEmpty(metadata.Composer)) { _atoms.Add(new TextAtom("©wrt", metadata.Composer)); } if (!string.IsNullOrEmpty(metadata.Genre)) { _atoms.Add(new TextAtom("©gen", metadata.Genre)); } if (!string.IsNullOrEmpty(metadata.Comment)) { _atoms.Add(new TextAtom("©cmt", metadata.Comment)); } if (!string.IsNullOrEmpty(metadata.Day) && !string.IsNullOrEmpty(metadata.Month) && !string.IsNullOrEmpty(metadata.Year)) { _atoms.Add(new TextAtom("©day", $"{metadata.Year}-{metadata.Month}-{metadata.Day}")); } else if (!string.IsNullOrEmpty(metadata.Year)) { _atoms.Add(new TextAtom("©day", metadata.Year)); } if (!string.IsNullOrEmpty(metadata.TrackNumber)) { _atoms.Add(new TrackNumberAtom(metadata.TrackNumber, metadata.TrackCount)); } if (metadata.CoverArt != null) { _atoms.Add(new CoverAtom(compressCoverArt ? CoverArtFactory.ConvertToLossy(metadata.CoverArt) : metadata.CoverArt)); } }
public List <Event> Generate(AudioMetadata audioMetadata) { var redColorTheme = StaticRandom.Rng.Next(2) == 0; var blueColorTheme = !redColorTheme; var lightEffects = new List <Event>(); var bpm = audioMetadata.BeatDetectorResult.BeatsPerMinute; var songIntensity = audioMetadata.BeatDetectorResult.SongIntensities; var continuousSongIntensity = new ContinuousLine2D(songIntensity.Select(x => new Point2D(x.SampleIndex, x.Intensity))); for (var beatIdx = 0; beatIdx < audioMetadata.BeatDetectorResult.RegularBeats.Count; beatIdx++) { if (beatIdx.IsOdd()) { continue; // Skip every second beat } var regularBeat = audioMetadata.BeatDetectorResult.RegularBeats[beatIdx]; var time = TimeConversion.SampleIndexToRealTime(regularBeat.SampleIndex, audioMetadata.SampleRate); var timeAsBeatIndex = TimeConversion.SampleIndexToBeatIndex(regularBeat.SampleIndex, audioMetadata.SampleRate, bpm); if (time > audioMetadata.Length - TimeSpan.FromSeconds(3)) { lightEffects.AddRange(TurnOffAllLights(timeAsBeatIndex)); break; } var currentIntensity = continuousSongIntensity.ValueAtX(regularBeat.SampleIndex); if (currentIntensity < 0.5) { var tunnelMove = StaticRandom.Rng.Next(2) == 0 ? EventType.TunnelRotation : EventType.TunnelZooming; lightEffects.Add(new Event { Time = timeAsBeatIndex, Type = tunnelMove, Value = StaticRandom.Rng.Next(10) }); } else { lightEffects.Add(new Event { Time = timeAsBeatIndex, Type = EventType.LightEffect0, Value = (int)(redColorTheme ? LightColor.RedFadeOut : LightColor.BlueFadeOut) }); lightEffects.Add(new Event { Time = timeAsBeatIndex, Type = EventType.LightEffect1, Value = (int)(redColorTheme ? LightColor.RedFadeOut : LightColor.BlueFadeOut) }); } } return(lightEffects); }
public async Task <AudioMetadata> GetAudioMetadata(AudioFileDoc audioFileDoc) { var storageFile = await StorageFile.GetFileFromPathAsync(audioFileDoc.FilePath); var fileMusicProperties = await storageFile.Properties.GetMusicPropertiesAsync(); var audioMetadata = new AudioMetadata(fileMusicProperties.Artist, fileMusicProperties.AlbumArtist, fileMusicProperties.Title); return(audioMetadata); }
public void generateThumbnail(MediaProbe mediaProbe, AudioMetadata audio, CancellationToken token, int timeoutSeconds, int nrThumbnails) { // get attached images List <MediaThumb> thumbBitmaps = mediaProbe.grabAttachedImages(Constants.MAX_THUMBNAIL_WIDTH, Constants.MAX_THUMBNAIL_HEIGHT, token, timeoutSeconds); if (thumbBitmaps.Count > 0) { audio.Thumbnail = new Thumbnail(thumbBitmaps[0].Thumb); } }
private IList <Note> GenerateModifiedBaseRhythm(Difficulty difficulty, AudioMetadata audioMetadata, out List <Obstacle> obstacles) { List <Beat> beats = audioMetadata.BeatDetectorResult.DetectedBeats; TimeSpan timeBetweenNotes = DetermineTimeBetweenNotes(difficulty); beats = FilterNotesByDifficulty(beats, timeBetweenNotes, audioMetadata.SampleRate); var notes = baseRhythmGenerator.Generate(beats, out obstacles, audioMetadata); return(notes); }
internal AudioMetadata GenerateAudioMetadata(PSB psb, string name, PsbDictionary voice, FreeMountContext context) { var md = new AudioMetadata(); md.Name = name; if (voice["file"] is PsbString fileStr) { md.FileString = fileStr; } if (voice["loopStr"] is PsbString loopStr) { md.LoopStr = loopStr; } if (voice["loop"] is PsbNumber loopNum) { md.Loop = loopNum.IntValue; } if (voice["quality"] is PsbNumber qualityNum) { md.Quality = qualityNum.IntValue; } if (voice["type"] is PsbNumber typeNum) { md.Type = typeNum.IntValue; } if (voice["device"] is PsbNumber deviceNum) { md.Device = deviceNum.IntValue; } if (voice["channelList"] is PsbList channelList) { foreach (var channel in channelList) { if (channel is PsbDictionary channelDic) { if (context.TryGetArchData(psb, channelDic, out var archData)) { archData.PsbArchData = channelDic; md.ChannelList.Add(archData); } } } } return(md); }
private void selfText(AudioMetadata obj) { Task.Run(() => { while (!(obj.Track?.IsLoaded ?? false)) { ; } hoverTimeText.Text = formatTime(TimeSpan.FromMilliseconds(obj.Track?.Length ?? 0) * hoverTimeText.Position.X); totalTimeText.Text = formatTime(TimeSpan.FromMilliseconds(obj.Track?.Length ?? 0)); }); }
public void Initialize(Stream stream, AudioInfo info, AudioMetadata metadata, SettingDictionary settings) { _stream = stream; _metadata = metadata; _settings = settings; InitializeReplayGainFilter(info, metadata, settings); var inputDescription = GetInputDescription(info); _audioFile = new(GetOutputDescription(inputDescription), AudioFileType.M4A, stream); _audioFile.SetProperty(ExtendedAudioFilePropertyId.ClientDataFormat, inputDescription); var converter = _audioFile.GetProperty <IntPtr>(ExtendedAudioFilePropertyId.AudioConverter); var logger = LoggerManager.LoggerFactory.CreateLogger <AacAudioEncoder>(); // Enable high quality (defaults to medium, 0x40) SetConverterProperty(converter, AudioConverterPropertyId.CodecQuality, 0x60); if (settings.TryGetValue("BitRate", out int bitRate)) { switch (bitRate) { case > 256 when info.Channels == 1: logger.LogWarning("The maximum bitrate for 1-channel audio is 256 kbps."); bitRate = 256; break; case < 64 when info.Channels == 2: logger.LogWarning("The minimum bitrate for 2-channel audio is 64 kbps."); bitRate = 64; break; } SetConverterProperty(converter, AudioConverterPropertyId.BitRate, bitRate * 1000); // Set the control mode (constrained is the default) var controlMode = BitrateControlMode.VariableConstrained; if (settings.TryGetValue("ControlMode", out string?controlModeValue)) { if (controlModeValue !.Equals("Average", StringComparison.OrdinalIgnoreCase)) { controlMode = BitrateControlMode.LongTermAverage; } else if (controlModeValue.Equals("Constant", StringComparison.OrdinalIgnoreCase)) { controlMode = BitrateControlMode.Constant; } } SetConverterProperty(converter, AudioConverterPropertyId.BitRateControlMode, (uint)controlMode); }
protected override void InitializeInternal() { AudioMetadata = Editor.IOComponent.LoadData <AudioMetadata>(SongDataFileUtility.TryGetAudioMetadata, "audio metadata"); if (AudioMetadata == null) { AudioMetadata = new AudioMetadata(); } DoSetStartingDelay(AudioMetadata.StartingDelay); RegisterTrackAndInitialize(AudioMetadata.BpmChanges, BpmChangeTrack); RegisterTrackAndInitialize(AudioMetadata.SectionNames, SectionNameTrack); }
void InitializeReplayGainFilter(AudioInfo info, AudioMetadata metadata, SettingDictionary settings) { var filterFactory = ExtensionProvider.GetFactories <IAudioFilter>("Name", "ReplayGain").FirstOrDefault(); if (filterFactory == null) { return; } _replayGainExport = filterFactory.CreateExport(); _replayGainExport.Value.Initialize(info, metadata, settings); }
private void play(bool next) { AudioMetadata meta = metadataList[next ? ++index : --index]; meta.InitializeComponents(storage); proyect.Audio.Track.AddItemToList(meta.Track); if (proyect.Metadata.Value?.Track != null) { proyect.Metadata.Value.Track.Stop(); proyect.Metadata.Value.Track.Dispose(); } proyect.Metadata.Value = meta; meta.Track.Restart(); }
private IList <Note> GenerateModifiedBaseRhythm(Difficulty difficulty, AudioMetadata audioMetadata) { var beats = BeatMerger.Merge( audioMetadata.BeatDetectorResult.DetectedBeats, audioMetadata.BeatDetectorResult.RegularBeats, audioMetadata.SampleRate); var startBeatIdx = beats.FindIndex(beat => beat.Strength > 0); var endBeatIdx = beats.FindLastIndex(beat => beat.Strength > 0); var totalValidBeatCount = endBeatIdx - startBeatIdx + 1; var barCount = totalValidBeatCount / audioMetadata.BeatDetectorResult.BeatsPerBar; var notes = baseRhythmGenerator.Generate(audioMetadata.BeatDetectorResult.BeatsPerBar, barCount, startBeatIdx); var difficultyFilteredNotes = FilterNotesByDifficulty(notes, audioMetadata, difficulty); return(difficultyFilteredNotes); }
public void Initialize(AudioInfo info, AudioMetadata metadata, SettingDictionary settings) { if (settings.TryGetValue("ApplyGain", out string applyGain)) { _scale = applyGain.Equals("Track", StringComparison.OrdinalIgnoreCase) ? CalculateScale(metadata.TrackGain, metadata.TrackPeak) : CalculateScale(metadata.AlbumGain, metadata.AlbumPeak); } // Adjust the metadata so that it remains valid metadata.TrackPeak = CalculatePeak(metadata.TrackPeak, _scale); metadata.AlbumPeak = CalculatePeak(metadata.AlbumPeak, _scale); metadata.TrackGain = CalculateGain(metadata.TrackGain, _scale); metadata.AlbumGain = CalculateGain(metadata.AlbumGain, _scale); }
void getAudioProperties(ObservableCollection <Tuple <String, String> > p, AudioMetadata audio) { p.Add(new Tuple <string, string>("", "AUDIO")); p.Add(new Tuple <string, string>("Audio Container", audio.AudioContainer)); p.Add(new Tuple <string, string>("Duration", MiscUtils.formatTimeSeconds(audio.DurationSeconds))); p.Add(new Tuple <string, string>("Audio Codec", audio.AudioCodec)); p.Add(new Tuple <string, string>("Bits Per Sample", audio.BitsPerSample.ToString())); p.Add(new Tuple <string, string>("Samples Per Second", audio.SamplesPerSecond.ToString())); p.Add(new Tuple <string, string>("Nr Channels", audio.NrChannels.ToString())); if (audio.BitRate.HasValue) { p.Add(new Tuple <string, string>("Rate", MiscUtils.formatSizeBytes(audio.BitRate.Value / 8) + "/s")); } }
public void LoadMetadataRefreshesMetadata([NotNull] string fileName) { var audioFile = new TaggedAudioFile(Path.Combine( new DirectoryInfo(Directory.GetCurrentDirectory()).Parent?.Parent?.Parent?.Parent?.FullName, "TestFiles", "Valid", fileName)); var expectedMetadata = new AudioMetadata(audioFile.Metadata); audioFile.Metadata.Title = "Modified"; audioFile.LoadMetadata(); Assert.True(new Comparer().Compare(expectedMetadata, audioFile.Metadata, out var differences), string.Join(" ", differences)); }
private List <Note> FilterNotesByDifficulty(IEnumerable <Note> baseNotes, AudioMetadata audioMetadata, Difficulty difficulty) { var songIntensities = audioMetadata.BeatDetectorResult.SongIntensities; var bpm = audioMetadata.BeatDetectorResult.BeatsPerMinute; var sampleRate = audioMetadata.SampleRate; var continuousSongIntensity = new ContinuousLine2D(songIntensities.Select(x => new Point2D(x.SampleIndex, x.Intensity))); var minimumTimeBetweenNotes = DetermineTimeBetweenNotes(difficulty); var notes = new List <Note>(); Note lastNote = null; foreach (var baseNote in baseNotes) { var noteTime = TimeConversion.BeatIndexToRealTime(baseNote.Time, bpm); var noteTimeInSamples = noteTime.TotalSeconds * sampleRate; if (noteTime < TimeSpan.FromSeconds(3)) { continue; // Stop a few seconds before song ends } if (noteTime > audioMetadata.Length - TimeSpan.FromSeconds(3)) { break; // Stop a few seconds before song ends } var currentIntensity = continuousSongIntensity.ValueAtX(noteTimeInSamples); if (lastNote != null) { var timeSinceLastBeat = noteTime - TimeConversion.BeatIndexToRealTime(lastNote.Time, bpm); if (currentIntensity.IsNaN()) { currentIntensity = 0; } var intensityAdjustment = TimeSpan.FromSeconds(0.5 * (1 - currentIntensity)); if (timeSinceLastBeat < minimumTimeBetweenNotes + intensityAdjustment && !AreSimultaneous(baseNote, lastNote)) { continue; } } var noteProbability = currentIntensity < 0.3 ? 0 : currentIntensity; if (StaticRandom.Rng.NextDouble() > noteProbability) { continue; } notes.Add(baseNote); lastNote = baseNote; } return(notes); }