public string Begin(IScriptableApp app)
    {
        //start MODIFY HERE-----------------------------------------------
           string szType  = GETARG("type", ".mp3"); //choose any valid extension: .avi  .wav  .w64 .mpg .mp3 .wma .mov .rm .aif .ogg .raw .au .dig .ivc .vox .pca
           object vPreset = GETARG("preset", ""); //put the name of the template between the quotes, or leave blank to pop the Template chooser.
           string szDir   = GETARG("dir", ""); //hardcode a target path here

           // GETARG is a function that defines the default script settings. You can use the Script Args field to over-ride
           // the values within GETARG().
           // Example: To over-ride GETARG(Key, valueA), type Key=valueB in the Script Args field.
           //          Use an ampersand (&) to separate different Script Args: KeyOne=valueB&KeyTwo=valueC

           //Example Script Args: type=.wav&dir=f:\RegionFiles

           //end MODIFY HERE -----------------------------------

           ISfFileHost file = app.CurrentFile;
           if (null == file)
          return "Open a file containing regions before running this script. Script stopped.";
           if (null == file.Markers || file.Markers.Count <= 0)
          return "The file does not have any markers.";

           bool showMsg = true;
           if (szDir == null || szDir.Length <= 0)
           {
          szDir = SfHelpers.ChooseDirectory("Select the target folder for saved files:", @"C:\");
          showMsg = false;
           }
           if (szDir == null || szDir.Length <= 0)
          return "no output directory";

           //make sure the directory exists
           if(!Path.IsPathRooted(szDir))
           {
          string szBase2 = Path.GetDirectoryName(file.Filename);
          szDir = Path.Combine(szBase2, szDir);
           }

           Directory.CreateDirectory(szDir);

           ISfRenderer rend = null;
           if (szType.StartsWith("."))
           rend = app.FindRenderer(null, szType);
           else
           rend = app.FindRenderer(szType, null);

           if (null == rend)
          return String.Format("renderer for {0} not found.", szType);

           // if the preset parses as a valid integer, then use it as such, otherwise assume it's a string.
           try {
           int iPreset = int.Parse((string)vPreset);
           vPreset = iPreset;
           } catch (FormatException) {}

           ISfGenericPreset template = null;
           if ((string)vPreset != "")
          template = rend.GetTemplate(vPreset);
           else
          template = rend.ChooseTemplate((IntPtr)null, vPreset);
           if (null == template)
          return "Template not found. Script stopped.";

           string szBase = file.Window.Title;
           //check to see if the window title contains a file extension. If so, remove it for save name. Remove this if you want that extension.
           if (szBase.Contains("."))
           {
           int indexOf = szBase.LastIndexOf('.');
           szBase = szBase.Remove(indexOf, (szBase.Length - indexOf));
           }

           // JH adding this counter in order to keep track of count for naming files which is not always consecutive when having markers and regions in file
           int counter = 1;

           // calculate the number of regions
           // wish I could do this without two loops
           int numberOfRegions = 0;
           foreach (SfAudioMarker mk in file.Markers)
           {
          if (mk.Length <= 0)
         continue;
          numberOfRegions++;
           }

           // loop through all markers and generate files from regions
           foreach (SfAudioMarker mk in file.Markers)
           {
          if (mk.Length <= 0)
         continue;

          // set filename to TwoDigitTrackNumber-originalFileTitle-RegionName.mp3
          string szName = String.Format("{0}-{1}-{2}.{3}", counter.ToString("00"), szBase, mk.Name, rend.Extension);

          szName = SfHelpers.CleanForFilename(szName);
          DPF("Queueing: '{0}'", szName);

          string szFullName = Path.Combine(szDir, szName);
          if (File.Exists(szFullName))
          File.Delete(szFullName);

          SfAudioSelection  range = new SfAudioSelection(mk.Start, mk.Length);

          // set the name and track metadata for the output mp3
          // all other mp3 metadata will come from the template; which the user selected
          file.Summary.Title = mk.Name;
          file.Summary.TrackNo = String.Format("{0}/{1}",counter.ToString(), numberOfRegions.ToString());

          file.RenderAs(szFullName, rend.Guid, template, range, RenderOptions.RenderOnly);
          DPF("Path: '{0}'", szFullName);

          // increment the track number counter
          counter++;
           }

           // remove the summary info we set on the file
           file.Summary.Title = "";
           file.Summary.TrackNo = "";

           if(showMsg)
          MessageBox.Show(String.Format("Files are saving to: {0}", szDir), "Status", MessageBoxButtons.OK, MessageBoxIcon.Information);

           return null;
    }
    public string Begin(IScriptableApp app)
    {
        //start MODIFY HERE-----------------------------------------------
           string szType  = GETARG("type", ".flac"); //choose any valid extension: .avi  .wav  .w64 .mpg .mp3 .wma .mov .rm .aif .ogg .raw .au .dig .ivc .vox .pca
           object vPreset = GETARG("preset", "44,100 Hz, 16 Bit, Stereo Highest Compression"); //put the name of the template between the quotes, or leave blank to pop the Template chooser.
           string szDir   = GETARG("dir", ""); //hardcode a target path here

           // GETARG is a function that defines the default script settings. You can use the Script Args field to over-ride
           // the values within GETARG().
           // Example: To over-ride GETARG(Key, valueA), type Key=valueB in the Script Args field.
           //          Use an ampersand (&) to separate different Script Args: KeyOne=valueB&KeyTwo=valueC

           //Example Script Args: type=.wav&dir=f:\RegionFiles

           //end MODIFY HERE -----------------------------------

           ISfFileHost file = app.CurrentFile;
           if (null == file)
          return "Open a file containing regions before running this script. Script stopped.";
           if (null == file.Markers || file.Markers.Count <= 0)
          return "The file does not have any markers.";

           bool showMsg = true;
           if (szDir == null || szDir.Length <= 0)
           {
          szDir = SfHelpers.ChooseDirectory("Select the target folder for saved files:", @"C:\");
          showMsg = false;
           }
           if (szDir == null || szDir.Length <= 0)
          return "no output directory";

           //make sure the directory exists
           if(!Path.IsPathRooted(szDir))
           {
          string szBase2 = Path.GetDirectoryName(file.Filename);
          szDir = Path.Combine(szBase2, szDir);
           }

           Directory.CreateDirectory(szDir);

           ISfRenderer rend = null;
           if (szType.StartsWith("."))
           rend = app.FindRenderer(null, szType);
           else
           rend = app.FindRenderer(szType, null);
           if (null == rend)
          return String.Format("renderer for {0} not found.", szType);

           // if the preset parses as a valid integer, then use it as such, otherwise assume it's a string.
           try {
           int iPreset = int.Parse((string)vPreset);
           vPreset = iPreset;
           } catch (FormatException) {}

           ISfGenericPreset template = null;
           if ((string)vPreset != "")
          template = rend.GetTemplate(vPreset);
           else
          template = rend.ChooseTemplate((IntPtr)null, vPreset);
           if (null == template)
          return "Template not found. Script stopped.";

           string szBase = file.Window.Title;
           int count = 1;

           foreach (SfAudioMarker mk in file.Markers)
           {
          if (mk.Length <= 0)
         continue;

          string szName = String.Format("{0}d1t{1}.{2}", szBase, count.ToString("00"), rend.Extension);
          szName = SfHelpers.CleanForFilename(szName);
          DPF("Queueing: '{0}'", szName);

          string szFullName = Path.Combine(szDir, szName);
          if (File.Exists(szFullName))
          File.Delete(szFullName);

          SfAudioSelection  range = new SfAudioSelection(mk.Start, mk.Length);
          file.RenderAs(szFullName, rend.Guid, template, range, RenderOptions.RenderOnly);
          DPF("Path: '{0}'", szFullName);

          count++;

           }

           if(showMsg)
          MessageBox.Show(String.Format("Files are saving to: {0}", szDir), "Status", MessageBoxButtons.OK, MessageBoxIcon.Information);

           return null;
    }
Exemple #3
0
 public void CopySelectionToStart(IScriptableApp app, SfAudioSelection selection)
 {
     _file.Window.SetSelectionAndScroll(selection.Start, selection.Length, DataWndScrollTo.NoMove);
     app.DoMenuAndWait("Edit.Copy", false);
     _file.Window.SetCursorAndScroll(0, DataWndScrollTo.NoMove);
     app.DoMenuAndWait("Edit.Paste", false);
 }
Exemple #4
0
        public void ApplyEffectPreset(IScriptableApp app, SfAudioSelection selection, string effectName, string presetName, EffectOptions effectOption, OutputHelper.MessageLogger logger)
        {
            if (effectOption == EffectOptions.ReturnPreset || effectOption == EffectOptions.WaitForDoneOrCancel)
            {
                throw new ScriptAbortedException("Invalid EffectOptions option: " + effectOption);
            }

            ISfGenericEffect effect = app.FindEffect(effectName);

            if (effect == null)
            {
                throw new ScriptAbortedException(String.Format("Effect '{0}' was not found.", effectName));
            }

            ISfGenericPreset preset = effect.GetPreset(presetName);

            if (preset == null)
            {
                throw new ScriptAbortedException(String.Format("Preset '{0}' was not found for effect '{1}'.", presetName, effectName));
            }

            if (logger != null)
            {
                logger("Applying Effect '{0}', Preset '{1}'...", effect.Name, preset.Name);
            }

            _file.DoEffect(effectName, presetName, selection, effectOption | EffectOptions.WaitForDoneOrCancel | EffectOptions.ReturnPreset);
        }
Exemple #5
0
        public SfAudioSelection SelectAll()
        {
            SfAudioSelection selection = new SfAudioSelection(_file);

            SetSelection(selection);
            return(selection);
        }
Exemple #6
0
        protected override void Execute()
        {
            _file      = App.CurrentFile;
            _fileTasks = new FileTasks(_file);
            _fileTasks.EnforceStereoFileOpen();
            _fileTasks.ZoomOutFull();

            FileMarkersWrapper     markers = new FileMarkersWrapper(_file);
            TrackMarkerNameBuilder trackMarkerNameBuilder = new TrackMarkerNameBuilder();
            TrackMarkerFactory     markerAndRegionFactory = new TrackMarkerFactory(markers, Output, trackMarkerNameBuilder);

            _splitTrackList = new SplitTrackList(markerAndRegionFactory, markerAndRegionFactory, trackMarkerNameBuilder, markers, new TrackMarkerSpecifications(), Output);

            _vinylRipOptions     = new VinylRipOptions();
            _noiseprintSelection = _fileTasks.EnforceNoisePrintSelection(App, _vinylRipOptions.NoiseprintLengthSeconds);

            // TODO: aiming to get this to re-use the initialisation from VinylRip2, then once valid/initialized, throw up the confirm tracks form and do the existing processing/splitting
            // TODO: validate tracks

            DialogResult result = ConfirmTrackSplitsForm(Script.Application.Win32Window);

            if (result == DialogResult.Cancel)
            {
                return;
            }

            DoFinalAudioClean();
            Directory.CreateDirectory(_outputDirectory);

            _splitTrackList.InitTracks(_vinylRipOptions);
            _splitTrackList.DumpToScriptWindow();

            DoTrackSplitting(_splitTrackList, trackMarkerNameBuilder);
        }
Exemple #7
0
        //TODO: clear console
        //TODO: come up with a way of saving settings between script runs, and between the 2 scripts (save options to json?)
        protected override void Execute()
        {
            _file      = App.CurrentFile;
            _fileTasks = new FileTasks(_file);
            _fileTasks.EnforceStereoFileOpen();
            _fileTasks.ZoomOutFull();

            //TODO: retain marker positions in script and undo NOT working!
            //_file.UndosAreEnabled = true;
            //int undoId = _file.BeginUndo("PrepareAudio");
            //_file.EndUndo(undoId, true);

            _vinylRipOptions     = new VinylRipOptions();
            _noiseprintSelection = _fileTasks.EnforceNoisePrintSelection(App, _vinylRipOptions.NoiseprintLengthSeconds);

            _file.Markers.Add(new SfAudioMarker(_noiseprintSelection));
            CleanVinylRecording(AggressiveCleaningPreset, 3, _noiseprintSelection); //TODO: configure number of noise reduction passes?

            _vinylRipOptions.StartScanFilePositionInSamples = _file.SecondsToPosition(_vinylRipOptions.NoiseprintLengthSeconds);

            _trackList = FindTracks(App, _file);

            App.DoMenuAndWait("Edit.UndoAll", false);

            FileMarkersWrapper markers       = new FileMarkersWrapper(_file);
            TrackMarkerFactory regionFactory = new TrackMarkerFactory(markers, Output, new TrackMarkerNameBuilder());

            foreach (TrackDefinition track in _trackList)
            {
                regionFactory.CreateRegion(track.Number, track.StartPosition, track.Length);
            }
        }
Exemple #8
0
        private List <ScanResult> DoStatisticsScan(long scanWindowLength, long startPosition, long scanEndPosition, long windowOverlap)
        {
            long windowCount = 1;

            bool scannedToEnd         = false;
            List <ScanResult> results = new List <ScanResult>();

            while (!scannedToEnd)
            {
                long selectionEnd = startPosition + scanWindowLength;
                if (selectionEnd >= scanEndPosition)
                {
                    selectionEnd = scanEndPosition;
                    scannedToEnd = true;
                }
                //Output.ToScriptWindow("Start={0} End={1}", selectionStart, selectionEnd);
                SfAudioSelection windowedSelection = WindowTasks.NewSelectionUsingEndPosition(startPosition, selectionEnd);

                ScanResult result = new ScanResult();
                result.WindowNumber   = windowCount;
                result.SelectionStart = startPosition;
                result.SelectionEnd   = selectionEnd;
                result.Ch1Statistics  = _fileTasks.GetChannelStatisticsOverSelection(0, windowedSelection);
                result.Ch2Statistics  = _fileTasks.GetChannelStatisticsOverSelection(1, windowedSelection);
                results.Add(result);

                Output.ToStatusField1("{0}", windowCount);
                Output.ToStatusField2("{0}s", OutputHelper.FormatToTimeSpan(_file.PositionToSeconds(startPosition)));
                startPosition = selectionEnd + 1 - windowOverlap;
                windowCount++;
            }
            return(results);
        }
Exemple #9
0
 public static void SetSelectionEnd(SfAudioSelection selection, long ccEndIn)
 {
     if (selection == null || ccEndIn < selection.Start)
     {
         return;
     }
     selection.Length = ccEndIn - selection.Start;
 }
Exemple #10
0
        private void ZoomToCurrentTrackEnd()
        {
            long             selectionLength = CurrentTrack.FadeOutEndMarker.Start - MarkerHelper.GetMarkerEnd(CurrentTrack.TrackRegion);
            SfAudioSelection selection       = new SfAudioSelection(MarkerHelper.GetMarkerEnd(CurrentTrack.TrackRegion), selectionLength);

            _fileTasks.SetSelection(selection);
            _fileTasks.ZoomToShow(_fileTasks.ExpandSelectionAround(selection, ZoomPadding));
            _fileTasks.RedrawWindow();
        }
Exemple #11
0
        private void ZoomToCurrentTrackStart()
        {
            long             selectionLength = CurrentTrack.FadeInEndMarker.Start - CurrentTrack.TrackRegion.Start;
            SfAudioSelection selection       = new SfAudioSelection(CurrentTrack.TrackRegion.Start, selectionLength);

            _fileTasks.SetSelection(selection);
            _fileTasks.ZoomToShow(_fileTasks.ExpandSelectionAround(selection, ZoomPadding));
            _fileTasks.RedrawWindow();
        }
Exemple #12
0
        public SfAudioStatistics GetChannelStatisticsOverSelection(uint channel, SfAudioSelection selection)
        {
            _file.UpdateStatistics(selection);
            SfStatus status = _file.WaitForDoneOrCancel();

            if (!_file.StatisticsAreUpToDate)
            {
                throw new ScriptAbortedException("Failed to update statistics for selection: {0} - {1} samples (WaitForDoneOrCancel returned \"{2}\")", status);
            }
            SfAudioStatistics statistics = _file.GetStatistics(channel);

            return(statistics);
        }
Exemple #13
0
        public SfAudioSelection EnforceNoisePrintSelection(IScriptableApp app, double noiseprintLength)
        {
            if (!IsCurrentSelectionGreaterThan(app, noiseprintLength))
            {
                throw new ScriptAbortedException("A noise selection of {0} seconds or more must be made before running this script.", noiseprintLength);
            }

            ISfDataWnd window = _file.Window;

            WindowTasks.SelectBothChannels(window);

            long             noiseprintSampleLength = _file.SecondsToPosition(noiseprintLength);
            SfAudioSelection selection = new SfAudioSelection(window.Selection.Start, noiseprintSampleLength, 0);

            return(selection);
        }
Exemple #14
0
        private void CleanVinylRecording(string presetName, int noiseReductionPasses, SfAudioSelection noiseprintSelection)
        {
            SfAudioSelection selection = _fileTasks.SelectAll();

            _fileTasks.ApplyEffectPreset(App, selection, EffectNames.ClickAndCrackleRemoval, presetName, EffectOptions.EffectOnly, Output.ToScriptWindow);
            for (int i = 1; i <= noiseReductionPasses; i++)
            {
                Output.ToScriptWindow("Noise Reduction (pass #{0})", i);
                EffectOptions noiseReductionOption = EffectOptions.EffectOnly;
                //if (i == 1)
                //    noiseReductionOption = EffectOptions.DialogFirst;
                _fileTasks.CopySelectionToStart(App, noiseprintSelection);
                _fileTasks.ApplyEffectPreset(App, selection, EffectNames.NoiseReduction, presetName, noiseReductionOption, Output.ToScriptWindow);
                _file.Window.SetSelectionAndScroll(0, _noiseprintSelection.Length, DataWndScrollTo.NoMove);
                App.DoMenuAndWait("Edit.Delete", false);
            }
            Output.LineBreakToScriptWindow();
        }
Exemple #15
0
        public SfAudioSelection ExpandSelectionAround(SfAudioSelection selection, long tryExpandBy)
        {
            SfAudioSelection newSelection = new SfAudioSelection(selection);

            newSelection.Start -= tryExpandBy;
            if (newSelection.Start < 0)
            {
                newSelection.Start = 0;
            }

            newSelection.Length += (2 * tryExpandBy);
            if (SelectionHelper.GetSelectionEnd(newSelection) > _file.Length)
            {
                SelectionHelper.SetSelectionEnd(newSelection, _file.Length);
            }

            return(newSelection);
        }
Exemple #16
0
 public void SetSelection(SfAudioSelection selection)
 {
     SetSelection(selection, DataWndScrollTo.NoMove);
 }
Exemple #17
0
 public void SetSelection(SfAudioSelection selection, DataWndScrollTo scrollTo)
 {
     _file.Window.SetSelectionAndScroll(selection.Start, selection.Length, scrollTo);
 }
Exemple #18
0
    public void makeButton_Click(object sender, EventArgs e)
    {
        // pull our segments out of the listbox for processing
        List<string> segments = new List<string>();
        if (listBox1.Items.Count > 0)
        {
            segments = listBoxItemsToStringList(listBox1, segDictionary);
        }
        else
        {
            MessageBox.Show("There are no VO segments selected.");
            return;
        }

        // get our total VO length
        double segsLength = FindSegsLength(segments, appl);
        // check to make sure our VO isn't longer than our total project length
        if (segsLength > newProfile.ProjectLength)
        {
            MessageBox.Show("The total length of the VO segments is larger than the total project length.\n" +
                "Either remove VO segments or increase the Project Length.");
            return;
        }

        //get the length of silence between segments
        double amtSilence = FindSilenceLength(newProfile.ProjectLength, segsLength, segments.Count);

        if (!haveMusicFilePath)
        {
            MessageBox.Show("You didn't select a music file.");
            return;
        }

        if (!newProfile.HaveDuckLevel)
        {
            MessageBox.Show("You didn't enter a valid Duck Level.");
            return;
        }

        //Lay our music bed down in our output file
        ISfFileHost musicFile = appl.OpenFile(musicFilePath, false, true);
        // make sure our music file is in correct format
        ResampleAndMono(musicFile, appl, 44100);

        SfAudioSelection music = new SfAudioSelection(musicFile);

        long prodLength = musicFile.SecondsToPosition(newProfile.ProjectLength);

        ISfFileHost outFile = appl.NewFile(musicFile.DataFormat, false);

        // Paste our music file into the out file until it is longer than the total prod length.
        while (outFile.Length < prodLength)
        {
            outFile.OverwriteAudio(outFile.Length, 0, musicFile, music);
        }

        musicFile.Close(CloseOptions.DiscardChanges);

        //crop our outFile to the desired length.
        outFile.CropAudio(0, prodLength);

        //Normalize the music volume to a comfortable level.
        int normLevel = -24;    //might replace with user selectable value
        bool normRMS = true;    //replace with user selection?

        appl.DoEffect("Normalize", GetNormPreset(appl, normLevel, normRMS), EffectOptions.EffectOnly | EffectOptions.WaitForDoneOrCancel);

        //Get the start position for our mixing operation.
        double startPosition = amtSilence / 2;

        // Fade out music at the end of our file
        double fadeLength = 2.0;
        if (startPosition < 2)
        {
            fadeLength = startPosition / 2;
        }
        Int64 ccFade = outFile.Length - outFile.SecondsToPosition(fadeLength);
        outFile.DoEffect("Graphic Fade", "-6dB exponential fade out", new SfAudioSelection(ccFade, outFile.Length), EffectOptions.EffectOnly);

        long pasteSec = outFile.SecondsToPosition(startPosition);
        SfAudioCrossfade cFade = new SfAudioCrossfade(outFile.SecondsToPosition(.175));
        double level = SfHelpers.dBToRatio(newProfile.DuckLevel);

        // Begin mixing our segments in.
        foreach (string file in segments)
        {
            ISfFileHost segment = appl.OpenFile(file, false, true);

            //remove any markers from the segment and add marker with the filename
            segment.Markers.Clear();
            segment.Markers.AddMarker(0, Path.GetFileName(file));

            // resample to 44100Hz and make sure the file is mono to match music
            ResampleAndMono(segment, appl, 44100);

            SfAudioSelection pasteSection = new SfAudioSelection(pasteSec, segment.Length);

            outFile.DoMixReplace(pasteSection, level, 1, segment, SfAudioSelection.All, cFade, cFade, EffectOptions.EffectOnly | EffectOptions.WaitForDoneOrCancel);

            pasteSec += (segment.Length + outFile.SecondsToPosition(amtSilence));
            segment.Close(CloseOptions.DiscardChanges);
        }

        outFile.Save(SaveOptions.AlwaysPromptForFilename);
        outFile.Close(CloseOptions.SaveChanges);
    }
Exemple #19
0
 public void ZoomToShow(SfAudioSelection selection)
 {
     _file.Window.ZoomToShow(selection.Start, selection.Length);
 }
Exemple #20
0
 public static string PrettyPrint(SfAudioSelection selection)
 {
     return($"Start: {selection.Start}, End: {GetSelectionEnd(selection)}, Length: {selection.Length}");
 }
Exemple #21
0
 public static long GetSelectionEnd(SfAudioSelection selection)
 {
     return(selection.Start + selection.Length);
 }