Exemplo n.º 1
0
        /// <summary>
        /// Advances the enumerator to the next element of the collection.
        /// </summary>
        /// <param name="item">The current item when advancing was successful.</param>
        /// <returns><c>true</c> whilst there are items within the collection; <c>false</c> if the collection has no items.</returns>
        public bool TryMoveNext(out AudioFileInfo item)
        {
            lock (this._syncRoot)
            {
                if (this.Playlist.Count == 0)
                {
                    item = null;
                    return(false);
                }

                this.SequenceIndex++;
                if (this.SequenceIndex < 0 ||
                    this.SequenceIndex == this.Playlist.Count)
                {
                    this.Reset();
                    this.SequenceIndex++;
                }

                try
                {
                    item = this.Playlist[this.CurrentIndex];
                    return(true);
                }
                catch (IndexOutOfRangeException)
                {
                    item = null;
                    return(false);
                }
            }
        }
        protected override void OnDoWork(DoWorkEventArgs e)
        {
            ReportProgress(0, SortingState.Start);

            TableController tableController = new TableController();
            AudioFileInfo   audioFile       = new AudioFileInfo();

            tableController.InsertInitialize();

            while (FileListEnumerator.MoveNext())
            {
                if (CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }

                FileInfo currentFile = new FileInfo(FileListEnumerator.Key.ToString());

                audioFile.GetInfo(currentFile);
                tableController.Insert(currentFile, audioFile);
            }

            ReportProgress(100, "Done!");
            e.Result = SortingState.Completed;
        }
Exemplo n.º 3
0
        public void Insert(FileInfo fileInfo, AudioFileInfo audioFileInfo)
        {
            using (SqlConnection connection = DBConnectionFactory.GetConnection())
            {
                connection.Open();

                using (SqlCommand insertCommand = new SqlCommand(@"TrackInsert_SP", connection))
                {
                    insertCommand.CommandType = CommandType.StoredProcedure;

                    #region satelite table values

                    int          result1 = InsertValueByTableName(fileInfo.DirectoryName, TableList.Path);
                    SqlParameter PathID  = new SqlParameter("@PathID", result1);
                    insertCommand.Parameters.Add(PathID);
                    PathID.Direction = ParameterDirection.Input;

                    int          result2  = InsertValueByTableName(audioFileInfo.Artist, TableList.Artist);
                    SqlParameter ArtistID = new SqlParameter("@ArtistID", result2);
                    insertCommand.Parameters.Add(ArtistID);
                    ArtistID.Direction = ParameterDirection.Input;

                    int          result3 = InsertValueByTableName(audioFileInfo.Album, TableList.Album);
                    SqlParameter AlbumID = new SqlParameter("@AlbumID", result3);
                    insertCommand.Parameters.Add(AlbumID);
                    AlbumID.Direction = ParameterDirection.Input;

                    int          result4 = InsertValueByTableName(audioFileInfo.Genre, TableList.Genre);
                    SqlParameter GenreID = new SqlParameter("@GenreID", result4);
                    insertCommand.Parameters.Add(GenreID);
                    GenreID.Direction = ParameterDirection.Input;

                    int          result5   = InsertValueByTableName(audioFileInfo.Bitrate, TableList.Bitrate);
                    SqlParameter BitrateID = new SqlParameter("@BitrateID", result5);
                    insertCommand.Parameters.Add(BitrateID);
                    BitrateID.Direction = ParameterDirection.Input;

                    #endregion

                    SqlParameter TrackTitle = new SqlParameter("@TrackTitle", audioFileInfo.Title);
                    insertCommand.Parameters.Add(TrackTitle);
                    TrackTitle.Direction = ParameterDirection.Input;

                    SqlParameter FileName = new SqlParameter("@FileName", fileInfo.Name);
                    insertCommand.Parameters.Add(FileName);
                    FileName.Direction = ParameterDirection.Input;

                    SqlParameter FileSize = new SqlParameter("@FileSize", fileInfo.Length);
                    insertCommand.Parameters.Add(FileSize);
                    FileSize.Direction = ParameterDirection.Input;

                    string       newName     = audioFileInfo.Artist + "_" + audioFileInfo.Title;
                    SqlParameter NewFileName = new SqlParameter("@NewFileName", newName);
                    insertCommand.Parameters.Add(NewFileName);
                    NewFileName.Direction = ParameterDirection.Input;

                    int affectedRows = (int)insertCommand.ExecuteNonQuery();
                }
            }
        }
Exemplo n.º 4
0
        public void Insert(FileInfo fileInfo, AudioFileInfo audioFileInfo)
        {
            Database database = (new DbFactory()).CreateDatabase();

            string spName = ((new Resources()).CreateInsertSPList())[TableList.Track].ToString();

            ExecuteStoredProcWithParam executeStoredProcWithParam =
                new ExecuteStoredProcWithParam(database, spName);

            executeStoredProcWithParam.AddInParameter(database,
                                                      InsertValueByTableName(fileInfo.DirectoryName, TableList.Path),
                                                      @"PathID");

            executeStoredProcWithParam.AddInParameter(database,
                                                      InsertValueByTableName(audioFileInfo.Artist, TableList.Artist),
                                                      @"ArtistID");

            executeStoredProcWithParam.AddInParameter(database,
                                                      InsertValueByTableName(audioFileInfo.Album, TableList.Album),
                                                      @"AlbumID");

            executeStoredProcWithParam.AddInParameter(database,
                                                      InsertValueByTableName(audioFileInfo.Genre, TableList.Genre),
                                                      @"GenreID");

            executeStoredProcWithParam.AddInParameter(database,
                                                      InsertValueByTableName(audioFileInfo.Bitrate, TableList.Bitrate),
                                                      @"BitrateID");

            executeStoredProcWithParam.AddInParameter(database,
                                                      audioFileInfo.Title,
                                                      @"TrackTitle");

            executeStoredProcWithParam.AddInParameter(database,
                                                      fileInfo.Name,
                                                      @"FileName");

            executeStoredProcWithParam.AddInParameter(database,
                                                      fileInfo.Length,
                                                      @"FileSize");

            string newName = string.Empty;

            if (string.IsNullOrEmpty(audioFileInfo.Artist) && string.IsNullOrEmpty(audioFileInfo.Title))
            {
                newName = fileInfo.Name;
            }
            else
            {
                newName = audioFileInfo.Artist + "_" + audioFileInfo.Title;
            }

            executeStoredProcWithParam.AddInParameter(database,
                                                      newName,
                                                      @"NewFileName");

            executeStoredProcWithParam.AddOutParameter(database, @"return_value");
            executeStoredProcWithParam.ExecuteSpSetResultValue(database, @"return_value");
        }
Exemplo n.º 5
0
        /// <inheritdoc/>
        protected override Task PlayAsync(AudioFileInfo file, CancellationToken cancellationToken)
        {
            _ = this.AudioPlayer
                .Clone()
                .PlayAsync(file, cancellationToken);

            return(Task.CompletedTask);
        }
Exemplo n.º 6
0
        public AudioFileInfo GetAudioFileInfo(string path)
        {
            _reader = new Mp3FileReader(path);
            var fileInfo = new FileInfo(path);

            var result = new AudioFileInfo
            {
                Name     = fileInfo.Name,
                Duration = _reader.TotalTime,
                FileSize = Math.Round((double)fileInfo.Length / 1000000, 2)
            };

            return(result);
        }
Exemplo n.º 7
0
        /// <summary>
        /// returns audio file information for a playlist item
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        private AudioFileInfo GetAudioFileInfo(ListViewItem item)
        {
            AudioFileInfo afInfo = null;

            try
            {
                if (item.Text != "")
                {
                    afInfo = new AudioFileInfo(item.SubItems[0].Text, item.SubItems[2].Text); //, TimeSpan.Zero);
                }
            }
            catch (Exception)
            {
                throw;
            }
            return(afInfo);
        }
Exemplo n.º 8
0
        /// <summary>
        /// returns the computed track order to play from playlist
        /// </summary>
        /// <param name="items">the items in the playlist</param>
        /// <returns></returns>
        public static List <PlayListEntry> ComputedRandomOrder(System.Windows.Forms.ListView.ListViewItemCollection items)
        {
            List <PlayListEntry> pltems = null;

            if (items != null)
            {
                int listSize = items.Count;
                if (listSize > 0)
                {
                    pltems = new List <PlayListEntry>();
                    List <int>    order    = new List <int>();
                    PlayListEntry entry    = new PlayListEntry();
                    Random        _rand    = new Random(DateTime.Now.Millisecond);
                    var           possible = Enumerable.Range(0, listSize).ToList();

                    /*var possible = Enumerable.Range(0, listSize)
                     *      .Select(r => _rand.Next(listSize))
                     *      .ToList();*/
                    //List<int> listNumbers = new List<int>();
                    for (int i = 0; i < listSize; i++)
                    {
                        int index = _rand.Next(0, possible.Count);
                        order.Add(possible[index]);
                        possible.RemoveAt(index);
                    }
                    foreach (int pos in order)
                    {
                        if (items[pos].Text != "")
                        {
                            AudioFileInfo afInfo = new AudioFileInfo(items[pos].SubItems[0].Text, items[pos].SubItems[2].Text);

                            PlayListEntry plIt = new PlayListEntry
                            {
                                FileName      = afInfo.FullPath,
                                HasPlayedOnce = false,
                                PosInPlayList = pos
                            };
                            pltems.Add(plIt);
                        }
                    }
                }
            }
            return(pltems);
        }
Exemplo n.º 9
0
        public static List<AudioFileInfo> GetAvailableFiles()
        {
            List<AudioFileInfo> files = new List<AudioFileInfo>();

            // Ensure the Music directory exists.
            Directory.CreateDirectory(Utils.MusicPath);

            foreach (string file in Directory.GetFiles(Utils.MusicPath, "*", SearchOption.AllDirectories))
            {
                AudioFileInfo fileInfo = new AudioFileInfo
                {
                    Name = Path.GetFileNameWithoutExtension(file),
                    Path = file,
                    FileExtension = Path.GetExtension(file)
                };
                files.Add(fileInfo);
            }
            return files;
        }
Exemplo n.º 10
0
        public static List <AudioFileInfo> GetAvailableFiles()
        {
            List <AudioFileInfo> files = new List <AudioFileInfo>();

            // Ensure the Music directory exists.
            Directory.CreateDirectory(Utils.MusicPath);

            foreach (string file in Directory.GetFiles(Utils.MusicPath, "*", SearchOption.AllDirectories))
            {
                AudioFileInfo fileInfo = new AudioFileInfo
                {
                    Name          = Path.GetFileNameWithoutExtension(file),
                    Path          = file,
                    FileExtension = Path.GetExtension(file)
                };
                files.Add(fileInfo);
            }
            return(files);
        }
Exemplo n.º 11
0
        private void l_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ListViewHitTestInfo info = l.HitTest(e.X, e.Y);
            ListViewItem        item = info.Item;

            if (item != null)
            {
                if (lastFileIdx >= 0)
                {
                    l.Items[lastFileIdx].ForeColor = l.Items[lastFileIdx].SubItems[1].ForeColor = Color.Black;
                }

                lastFileIdx        = item.Index;
                parent.UserStopped = false;
                AudioFileInfo afInfo   = GetAudioFileInfo(item);
                bool          hasQueue = StartPlaying(afInfo.FullPath, lastFileIdx);

                item.ForeColor = item.SubItems[1].ForeColor = Color.Blue;
                //parent.IsPlaylistRunning = true;

                if (!hasQueue && parent.AudioPlayer != null)
                {
                    if (l.Items[lastFileIdx].SubItems[1].Text == "")
                    {
                        l.Items[lastFileIdx].SubItems[1].Text = Utils.FormatTimeSpan2(parent.AudioPlayer.GetTotalTime());
                        l.Columns[1].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
                    }
                }

                //MessageBox.Show("The selected Item Name is: " + item.Text);
                OnPlaylistItemDoubleClicked(e);
            }
            else
            {
                this.l.SelectedItems.Clear();
                Invoke((Action)(() =>
                {
                    MessageBox.Show(this, "No Item is selected");
                }));
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// choose the next file to play by index
        /// </summary>
        /// <returns>true if the file must play, false otherwise</returns>
        public bool GetNextFileFromPlayList(/*out string nextFileToPlay*/)
        {
            string nFile = "";

            if (lastFileIdx < l.Items.Count)
            {
                Action action = () =>
                {
                    nFile = l.Items[lastFileIdx].Text;
                    AudioFileInfo afInfo = GetAudioFileInfo(l.Items[lastFileIdx]);
                    parent.AudioFile = afInfo.FullPath;
                };
                Invoke(action);
                return(true);
            }
            else
            {
                Action action = () => lastFileIdx = l.Items.Count - 1;
                Invoke(action);
                return(false);
            }
        }
Exemplo n.º 13
0
        void plWnd_PlaylistItemDoubleClicked(object sender, EventArgs e)
        {
            if (File.Exists(mAudioFile))
            {
                //IsPlaylistRunning = true;
                //plWnd.HasUserSelTrack = true;
                chkShuffle.Enabled = true;
                currentAudioFile   = plWnd.GetFileToPlay(plWnd.LastFileIdx);
                UpdateMarquee();
                ShowPopup();
                if (audioPlayer != null)
                {
                    //audioPlayer.PlaybackStopType = PlaybackStopTypes.PlaybackStoppedByUser;
                    if (audioPlayer.IsStopped())
                    {
                        if (!isWaitingHandle)
                        {
                            //InitPlayer();
                            //StartPlaybackThread();
                            userStopped = false;
                        }
                    }
                    if (isSingleFilePlaying)
                    {
                        isSingleFilePlaying = false;
                    }

                    Action action = () =>
                    {
                        btnRew.Enabled = btnFwd.Enabled = true;
                    };
                    Invoke(action);
                }
            }
            //if (audioPlayer != null)
            //    audioPlayer.PlaybackStopType = PlaybackStopTypes.PlaybackStoppedByUser;
        }
Exemplo n.º 14
0
        /// <summary>
        /// loads all available audio files inside the control
        /// </summary>
        private void LoadAudioFilesIntoPlWnd()
        {
            List <AudioFileInfo> filesList = new List <AudioFileInfo>();

            using (FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog())
            {
                string folderPath = "";
                //folderBrowserDialog1 = new FolderBrowserDialog();
                if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                {
                    Thread t = new Thread(delegate()
                    {
                        folderPath   = folderBrowserDialog1.SelectedPath;
                        var allFiles = DirSearch(folderPath);
                        foreach (string af in allFiles)
                        {
                            AudioFileInfo afInfo = new AudioFileInfo(Path.GetFileName(af), af);
                            //afInfo.SetDuration();
                            filesList.Add(afInfo);  //, TimeSpan.Zero));
                        }

                        Action action;
                        action = () =>
                        {
                            if (l.Items.Count > 0)
                            {
                                l.Items.Clear();
                            }

                            //l.Invoke(action);
                            int cnt = 0;
                            foreach (AudioFileInfo item in filesList)
                            {
                                ++cnt;

                                //add items to ListView
                                ListViewItem itm = new ListViewItem(new[] { string.Format("{0}. {1}", cnt.ToString("D3"), item.FileName), "" /*Utils.FormatTimeSpan2(item.FileLength)*/, item.FullPath });
                                l.Items.Add(itm);
                                //action = () => l.Items.Add(itm);
                                //l.Invoke(action);
                            }
                            if (l.Items.Count > 0)
                            {
                                l.AutoResizeColumn(l.Columns.Count - 1, ColumnHeaderAutoResizeStyle.ColumnContent);
                                UpdateButtons();
                                parent.IsPlaylistRunning = true;
                                lastFileIdx = -1;

                                lblPlistInfo.Text = string.Format("{0} files.",
                                                                  l.Items.Count);
                                lblPlistInfo.Visible = true;

                                this.btnClear.Enabled = true;
                                this.btnSave.Enabled  = true;

                                //PlaylistLoaded(this, null);

                                //lblPlistInfo.Text += string.Format(", Tot. Time: {0}:{1}",
                                //    (int)totPlaylistTime/60, (int)totPlaylistTime % 60);
                                //StartPlaying(l.Items[0].Text, 0);
                            }
                            else
                            {
                                lblPlistInfo.Text = string.Format("{0} files.", 0);
                            }
                            PlaylistLoaded(this, null);
                        };
                        Invoke(action);
                    });
                    t.Start();
                }
            }
        }
Exemplo n.º 15
0
        private void bgPlayWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled == true)
            {
                MessageBox.Show("Canceled!");
            }
            else if (e.Error != null)
            {
                MessageBox.Show("Error: " + e.Error.Message);
            }
            else
            {
                //Debug.WriteLine("BACKGROUND WORKER THREAD FINISHED.");

                isWaitingHandle = false;

                if (IsPlaylistRunning)
                {
                    if (isSingleFilePlaying) //!isSingleFilePlaying)
                    {
                        isSingleFilePlaying = false;
                    }
                    int aPos = -1;

                    if (plWnd.HasUserSelTrack)
                    {
                        aPos = plWnd.LastFileIdx;
                        plWnd.LastFileIdx = aPos;
                        //plWnd.HasUserSelTrack = false;
                    }
                    else
                    {
                        CurrentTrackCompleted(this, e);
                        if (!mIsShuffleChecked)
                        {
                            aPos = plWnd.LastFileIdx + 1;
                        }
                        else
                        {
                            aPos = randSongsIdx[((shuffleCnt + 1)) % plWnd.GetPlaylistSize()].PosInPlayList;
                            ++shuffleCnt;
                            if (shuffleCnt == plWnd.GetPlaylistSize())
                            {
                                shuffleCnt = 0;
                            }
                        }
                        plWnd.LastFileIdx = aPos;
                    }

                    if (aPos < plWnd.GetPlaylistSize())
                    {
                        currentAudioFile = plWnd.GetFileToPlay(aPos);
                        mAudioFile       = currentAudioFile.FullPath;

                        if (File.Exists(mAudioFile))
                        {
                            try
                            {
                                InitPlayer(true);
                                plWnd.HasUserSelTrack = false;
                                InitBgWorker();
                                StartPlaybackThread();
                                NextTrackStarted(this, e);
                                UpdateMarquee();
                                ShowPopup();
                            }
                            catch (Exception)
                            {
                                //throw;
                            }
                        }
                        //else
                        //    MessageBox.Show(string.Format("File {0} not found!", mAudioFile));
                        //++plWnd.LastFileIdx;
                    }
                    else
                    {
                        try
                        {
                            StopPlayback();
                        }
                        catch (Exception)
                        {
                            //throw;
                        }
                        plWnd.LastFileIdx = -1;
                        IsPlaylistRunning = false;
                        EnableButtons(false);
                    }
                    //}
                    //else
                    //    isSingleFilePlaying = false;
                }
                else
                {
                    //isWaitingHandle = true;
                    StopPlayback();
                    //StartPlaybackThread();
                    Action action = () =>
                    {
                        if (isSingleFilePlaying)
                        {
                            EnableButtons(false);
                        }
                        else
                        {
                            EnableButtons(true);
                        }
                    };
                    Invoke(action);
                }
                ((BackgroundWorker)sender).Dispose();
                GC.Collect();
                //MessageBox.Show("End of playback.");
            }
        }
Exemplo n.º 16
0
        private void btnPlay_Click(object sender, EventArgs e)
        {
            if (mAudioFile == null)
            {
                Thread t = new Thread(delegate()
                {
                    bool hasSelFile = SelectInputFile();
                    if (hasSelFile)
                    {
                        InitPlayer();
                        InitBgWorker();
                        StartPlaybackThread();
                        //if (audioPlayer != null)
                        //    audioPlayer.PlaybackStopType = PlaybackStopTypes.PlaybackStoppedReachingEndOfFile;
                        userStopped         = false;
                        isSingleFilePlaying = true;
                    }
                });
                t.Start();
            }
            else
            {
                try
                {
                    if (audioPlayer == null)
                    {
                        audioPlayer =
                            new LocalAudioPlayer(mAudioFile, GetSelectedOutputDriver());
                        audioPlayer.PlaybackStopType = PlaybackStopTypes.PlaybackStoppedReachingEndOfFile;
                        //audioPlayer.PlaybackPaused += audioPlayer_PlaybackPaused;
                        audioPlayer.PlaybackResumed += audioPlayer_PlaybackResumed;
                        //audioPlayer.PlaybackStopped += audioPlayer_PlaybackStopped;

                        if (!IsPlaylistRunning)
                        {
                            currentAudioFile = new AudioFileInfo(Path.GetFileName(mAudioFile), mAudioFile);
                        }

                        Action action = () =>
                        {
                            if (tbVolume.Value != VOL_INIT * 100)
                            {
                                audioPlayer.SetVolume((float)tbVolume.Value / 100f);
                            }
                            else
                            {
                                audioPlayer.SetVolume(VOL_INIT);
                            }
                        };
                        Invoke(action);

                        StartPlaybackThread();
                    }
                    else
                    {
                        if (aTimer != null && !aTimer.Enabled)
                        {
                            aTimer.Enabled = true;
                            aTimer.Start();
                        }
                        StartPlaybackThread();
                        audioPlayer.PlaybackStopType = PlaybackStopTypes.PlaybackStoppedReachingEndOfFile;
                    }
                }
                catch (Exception)
                {
                }
                userStopped = false;
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// init the audio player
        /// </summary>
        public void InitPlayer(bool dispose = true, PlaybackStopTypes pbStopType = PlaybackStopTypes.PlaybackStoppedReachingEndOfFile)
        {
            if (aTimer.Enabled)
            {
                aTimer.Stop();
                aTimer.Enabled = false;
            }

            Action action;

            //action = () =>
            //    {
            try
            {
                if (audioPlayer != null)
                {
                    //waitHandle.Set();
                    if (audioPlayer.IsPlaying() || audioPlayer.IsPaused())
                    {
                        audioPlayer.StopPlayback();
                    }
                    while (isWaitingHandle)
                    {
                    }
                    audioPlayer.PlaybackResumed -= audioPlayer_PlaybackResumed;
                    //audioPlayer.PlaybackStopped -= audioPlayer_PlaybackStopped;
                    if (dispose)
                    {
                        audioPlayer.Dispose();
                        audioPlayer = null;
                    }
                }
            }
            catch (Exception)
            {
                //throw;
            }
            //    };
            //Invoke(action);
            try
            {
                //if (audioPlayer == null)

                audioPlayer =
                    new LocalAudioPlayer(mAudioFile, GetSelectedOutputDriver());
                audioPlayer.PlaybackStopType = pbStopType;
                //audioPlayer.PlaybackPaused += audioPlayer_PlaybackPaused;
                audioPlayer.PlaybackResumed += audioPlayer_PlaybackResumed;
                //audioPlayer.PlaybackStopped += audioPlayer_PlaybackStopped;
                if (!IsPlaylistRunning)
                {
                    currentAudioFile = new AudioFileInfo(Path.GetFileName(mAudioFile), mAudioFile);
                }
            }
            catch (Exception)
            {
                action = () => MessageBox.Show(this, string.Format("Cannot load file '{0}'", mAudioFile));
                Invoke(action);
            }
            if (audioPlayer != null)
            {
                action = () =>
                {
                    if (tbVolume.Value != VOL_INIT * 100)
                    {
                        audioPlayer.SetVolume((float)tbVolume.Value / 100f);
                    }
                    else
                    {
                        audioPlayer.SetVolume(VOL_INIT);
                    }
                };
                tbVolume.Invoke(action);
                action = () => lblTotalTime.Text = Utils.FormatTimeSpan(audioPlayer.GetTotalTime());
                lblTotalTime.Invoke(action);
                action = () =>
                {
                    tbAudioPos.Value   = 0;
                    tbAudioPos.Maximum = (int)(audioPlayer.GetTotalTime().Minutes) * 60
                                         + audioPlayer.GetTotalTime().Seconds;
                    if (tbAudioPos.Maximum > 0)
                    {
                        tbAudioPos.Enabled = true;
                    }
                    else
                    {
                        tbAudioPos.Enabled = false;
                    }
                };
                tbAudioPos.Invoke(action);
                action = () =>
                {
                    UpdateMarquee();
                };
                Invoke(action);
            }
        }
        public static JObject GenerateRichMetadata(string filePath)
        {
            //Get file info
            var info = AudioFileInfo.GetAudioFileInfo(filePath);

            //Get details
            float durationSeconds = float.Parse(info.data["STREAM"]["duration"]);
            int   sampleRate      = int.Parse(info.data["STREAM"]["sample_rate"]);

            //Determine how many samples will be in each data point
            //This will break for very short audio files, but this will likely never be encountered
            float samplesPerDataPoint = (float)(sampleRate * durationSeconds) / (float)RESOLUTION;

            if (samplesPerDataPoint < 1)
            {
                throw new Exception("Audio is too short!");
            }

            //Start FFMPEG and instruct it to output in 8-bits-per-sample mono. This will mix down stereo tracks to mono
            string  args   = $"-i \"{filePath}\" -f s8 -acodec pcm_s8 -ac 1 -";
            Process ffmpeg = Process.Start(new ProcessStartInfo
            {
                FileName               = Program.site.config.ffmpeg_path,
                Arguments              = args,
                UseShellExecute        = false,
                RedirectStandardOutput = true
            });

            //Open file where we'll save this info
            long read = 0;

            using (FileStream fs = new FileStream(filePath + ".audiothumb", FileMode.Create))
            {
                //Run for resolution
                for (int j = 0; j < RESOLUTION; j += 1)
                {
                    //Deteremine how many to read
                    //Find the end byte
                    long endByte = (long)(j * samplesPerDataPoint);

                    //Find the max in these samples
                    byte max = 0;
                    while (read < endByte)
                    {
                        int value = (sbyte)ffmpeg.StandardOutput.BaseStream.ReadByte();
                        max = Math.Max(max, (byte)Math.Abs(value));
                        read++;
                    }

                    //Write
                    fs.WriteByte(max);
                }
            }

            //Wait for end
            ffmpeg.StandardOutput.BaseStream.Close();
            ffmpeg.WaitForExit();

            //Create rich metadata
            JObject meta = new JObject();

            meta["DURATION_SECONDS"]         = durationSeconds;
            meta["SAMPLE_RATE"]              = sampleRate;
            meta["CHANNELS"]                 = int.Parse(info.data["STREAM"]["channels"]);
            meta["AUDIO_THUMB_RESOLUTION"]   = RESOLUTION;
            meta["AUDIO_THUMB_VERSION"]      = 1;
            meta["AUDIO_THUMB_GENERATED_AT"] = DateTime.UtcNow.Ticks;
            return(meta);
        }
Exemplo n.º 19
0
        private void btnFwd_Click(object sender, EventArgs e)
        {
            if (isSingleFilePlaying)
            {
                return;
            }
            if (audioPlayer != null)
            {
                if (plWnd.LastFileIdx < plWnd.GetPlaylistSize() - 1)
                {
                    CurrentTrackCompleted(sender, e);

                    if (bgPlayWorker.IsBusy && isWaitingHandle)
                    {
                        isWaitingHandle = false;
                        waitHandle.Set();
                        //if (File.Exists(mAudioFile))
                        //    UpdateMarquee();
                    }
                    else
                    {
                        int nextPos = -1;
                        if (!mIsShuffleChecked)
                        {
                            nextPos = plWnd.LastFileIdx + 1;
                        }
                        else
                        {
                            if (plWnd.LastFileIdx < 0)
                            {
                                plWnd.LastFileIdx = 0;
                            }
                            nextPos = randSongsIdx[plWnd.LastFileIdx].PosInPlayList;
                        }
                        if (ResetPlayList(sender, e, nextPos))
                        {
                            IsPlaylistRunning            = true;
                            audioPlayer.PlaybackStopType = PlaybackStopTypes.PlaybackStoppedReachingEndOfFile;
                            userStopped      = false;
                            currentAudioFile = plWnd.GetFileToPlay(plWnd.LastFileIdx);
                            UpdateMarquee();
                            ShowPopup();
                        }
                    }
                }
                else
                {
                    if (plWnd.LastFileIdx == plWnd.GetPlaylistSize() - 1 && mIsShuffleChecked)
                    {
                        CurrentTrackCompleted(sender, e);

                        if (bgPlayWorker.IsBusy && isWaitingHandle)
                        {
                            isWaitingHandle = false;
                            waitHandle.Set();
                            //if (File.Exists(mAudioFile))
                            //    UpdateMarquee();
                        }
                        else
                        {
                            if (ResetPlayList(sender, e, 0))
                            {
                                IsPlaylistRunning            = true;
                                audioPlayer.PlaybackStopType = PlaybackStopTypes.PlaybackStoppedReachingEndOfFile;
                                userStopped      = false;
                                currentAudioFile = plWnd.GetFileToPlay(plWnd.LastFileIdx);
                                UpdateMarquee();
                                ShowPopup();
                            }
                        }
                    }
                }
            }
            else
            {
                int aPos = -1;
                if (!mIsShuffleChecked)
                {
                    aPos = 0;
                }
                else
                {
                    aPos = randSongsIdx[0].PosInPlayList;
                }
                if (ResetPlayList(sender, e, aPos))
                {
                    IsPlaylistRunning            = true;
                    audioPlayer.PlaybackStopType = PlaybackStopTypes.PlaybackStoppedReachingEndOfFile;
                    userStopped      = false;
                    currentAudioFile = plWnd.GetFileToPlay(plWnd.LastFileIdx);
                    UpdateMarquee();
                    ShowPopup();
                }
            }
        }