public static bool BackgroundEnqueue(SongType songtype, string Link, string RequestedBy, string title) { try { IWaveSource source = songtype == SongType.MP3 ? (IWaveSource) new Mp3MediafoundationDecoder(Link) : new AacDecoder(Link); var lenght = source.GetLength().TotalMinutes; if ((source.GetLength().TotalMinutes < Config.MaximumBackgroundInMin || Config.MaximumBackgroundInMin == 0) || Config.Admin == RequestedBy) { ConsoleSender.SendCommand($"{title} was added to the queue", ConsoleSender.Command.Chat); BackGroundQueue.PlayList.Enqueue(new Song(title, source, new User { Name = RequestedBy, Tag = 0 })); return(true); } else { Thread.Sleep(800); ConsoleSender.SendCommand("UwU sowwy butt its nyot possibwe to pway this swong", ConsoleSender.Command.Chat); ConsoleSender.SendCommand($"I can't handwe things that awe longer than {Instance.Config.MaximumBackgroundInMin} minyutes (inches) OwO", ConsoleSender.Command.Chat); return(true); } } catch (Exception e) { Console.WriteLine(e); return(false); } }
public TimeSpan Duracion() { if (FormatoSonido != FormatoSonido.OGG) { return(_sonido.GetLength()); } else { return(NVorbis.Duracion); } }
/// <summary> /// 获取音频文件开始到结束的时间间隔 /// </summary> /// <param name="filepath"></param> /// <returns>返回时间间隔</returns> private TimeSpan GetMusicTimeSpan(string filepath) { IWaveSource source = CodecFactory.Instance.GetCodec(filepath); TimeSpan musicTimeSpan = source.GetLength(); return(musicTimeSpan); }
public virtual async Task <bool> CheckTrack() { TimeSpan duration = TimeSpan.Zero; if (!TrackExists) { return(false); } try { await Task.Run(() => { using (IWaveSource soundSource = CodecFactory.Instance.GetCodec(Path)) { duration = soundSource.GetLength(); } }); SetDuration(duration); } catch (Exception) { return(false); } IsChecked = true; return(true); }
private void PlaybackStoppedEventTestInternal(ISoundOut soundOut, IWaveSource source) { for (int i = 0; i < basic_iteration_count; i++) { bool raised = false; soundOut.Stopped += (s, e) => raised = true; soundOut.Initialize(source); soundOut.Play(); Thread.Sleep((int)(source.GetLength().TotalMilliseconds + 50)); while (soundOut.PlaybackState != PlaybackState.Stopped) { ; } soundOut.Initialize(source); //the playbackstate may be stopped but event was not fired. initialize will wait until it gets fired. source.Position = 0; Assert.IsTrue(raised); raised = false; //check for event on eof soundOut.Play(); Thread.Sleep(50); soundOut.Stop(); Assert.IsTrue(raised); } }
public override float GetLengthInSeconds(string pathToSourceFile) { float duration = 0; lock (_lockObj) { try { using (IWaveSource soundSource = CodecFactory.Instance.GetCodec(pathToSourceFile)) { if (soundSource != null) { var time = soundSource.GetLength(); duration = (float)time.TotalSeconds; } else { throw new NotSupportedException("No working codecs found!"); } } } catch (System.Exception e) { throw new ArgumentException(string.Format("GetLengthInSeconds failed for {0}: {1}", pathToSourceFile, e.Message)); } } return(duration); }
public int Lengthms(AudioData audio) { IWaveSource ws = audio.data as IWaveSource; System.Diagnostics.Debug.Assert(ws != null); TimeSpan w = ws.GetLength(); return((int)w.TotalMilliseconds); }
public static TimeSpan GetLength(string filename) { IWaveSource source = CodecFactory.Instance.GetCodec(filename); TimeSpan length = source.GetLength(); source.Dispose(); return(length); }
void OpenMusic(string op) { // Instancia a janela de diálogo e define suas configurações OpenFileDialog ofd = new OpenFileDialog(); ofd.Multiselect = true; ofd.Filter = CSCore.Codecs.CodecFactory.SupportedFilesFilterEn; ofd.InitialDirectory = Environment.SpecialFolder.CommonMusic.ToString(); // Recebe o resultado da ação na janela DialogResult dr = ofd.ShowDialog(); if (dr == DialogResult.OK) { if (op == "open") { listView1.Items.Clear(); } foreach (var f in ofd.FileNames) { // Extrai o caminho completo do arquivo string flname = Path.GetFullPath(f); // Monta o Título do item int nmblist = listView1.Items.Count + 1; var file = CSCore.Tags.ID3.ID3v2.FromFile(flname.ToString()); string itmlist = nmblist + ". " + file.QuickInfo.LeadPerformers + " - " + file.QuickInfo.Title; // Extrai e monta o tempo total de cada item IWaveSource iw = CodecFactory.Instance.GetCodec(flname.ToString()); string len = iw.GetLength().Hours.ToString("00") + ":" + iw.GetLength().Minutes.ToString("00") + ":" + iw.GetLength().Seconds.ToString("00"); // Adiciona o item a ListView ListViewItem lvi = new ListViewItem(itmlist); lvi.SubItems.Add(len); lvi.SubItems.Add(flname); listView1.Items.Add(lvi); } } }
public int TimeLeftms(AudioData audio) { IWaveSource ws = audio.data as IWaveSource; System.Diagnostics.Debug.Assert(ws != null); TimeSpan l = ws.GetLength(); TimeSpan p = ws.GetPosition(); TimeSpan togo = l - p; return((int)togo.TotalMilliseconds); }
public static Track ToTrack(this IWaveSource wavesource) { return(new Track() { Duration = wavesource.GetLength(), Channel = (ChannelType)wavesource.WaveFormat.Channels, Encoding = wavesource.WaveFormat.WaveFormatTag, SampleRate = wavesource.WaveFormat.SampleRate, Sampling = wavesource.WaveFormat.BitsPerSample, }); }
public TimeSpan Duracion() { if (FormatoSonido != FormatoSonido.OGG) { return(_sound.GetLength()); } else if (FormatoSonido == FormatoSonido.CDA) { return(SectoresATimeSpan(_sound.Length)); } else { try { return(NVorbis.Length_Timespan); } catch (Exception) { } return(TimeSpan.Zero); } }
void UpdateMetadata(IWaveSource source) { // duration of the last track imported from a CUE sheet is not initially known; // update it now that we have audio source decoded; this update is only valid for the last track! if (_duration == TimeSpan.Zero) { var duration = source.GetLength(); _duration = duration - Offset; SetDuration(_duration); } kHz = source.WaveFormat.SampleRate / 1000; kbps = source.WaveFormat.BytesPerSecond * 8 / 1000; }
void UpdateMetadata(IWaveSource source) { // duration of the last track imported from a CUE sheet is not initially known; // update it now that we have audio source decoded; this update is only valid for the last track! if (_duration == TimeSpan.Zero) { var duration = source.GetLength(); _duration = duration - Offset; SetDuration(_duration); } kHz = source.WaveFormat.SampleRate / 1000; kbps = source.WaveFormat.BytesPerSecond * 8 / 1000; }
public void SeekScore(float position) { if (IsPlaying && currentMusic != null) { int newPosInMillis = (int)(currentMusic.GetLength().TotalMilliseconds *position); Console.WriteLine("Seeking to " + newPosInMillis); currentMusic.SetPosition(TimeSpan.FromMilliseconds(newPosInMillis)); UpdateMillis(); while (CurrentScore.Triggers[triggerIndex].time < CurrentMillis) { SkipNextTrigger(); } } }
public void Seek(double TrackPercent) { if (CurrentTrack == null) { return; } if (TrackPercent < 0 || TrackPercent > 1) { return; } TimeSpan targetTime = _waveSource.GetLength() * TrackPercent; _waveSource.SetPosition(targetTime); Seeked?.Invoke(TrackPercent); }
//Playing function public void playing() { if (db > 0) { //Init device.Stop(); int index = (int)playlist.list.CurrentRow.Cells[0].Value - 1; path = tracks[index]; if (paused == 0) { audio = CodecFactory.Instance.GetCodec(path); } device.Initialize(audio); device.Volume = (float)track_volume.Value / 10; device.Play(); paused = 0; //Getting audio information label_name.Text = Path.GetFileNameWithoutExtension(path); label_extension.Text = Path.GetExtension(path); label_progress.Text = "00:00"; label_length.Text = ""; length = (int)audio.GetLength().TotalSeconds; if (length / 60 < 10) { label_length.Text += "0" + length / 60 + ":"; } else { label_length.Text += length / 60 + ":"; } if (length % 60 < 10) { label_length.Text += "0" + length % 60; } else { label_length.Text += length % 60; } timer.Start(); } }
private void openAudioFileToolStripMenuItem_Click(object sender, EventArgs e) { if (ofd_music.ShowDialog() != DialogResult.OK) { return; } waveSource = CodecFactory.Instance.GetCodec(ofd_music.FileName) .ToSampleSource() .ToStereo() .ToWaveSource(); soundOut = GetSoundOut(); soundOut.Initialize(waveSource); tbar_pos.Maximum = (int)waveSource.GetLength().TotalMilliseconds; sfd_lrc.FileName = Path.GetFileNameWithoutExtension(ofd_music.FileName) + ".lrc"; }
private void CanHandleEOFTestInternal(ISoundOut soundOut, IWaveSource source) { int sourceLength = (int)source.GetLength().TotalMilliseconds; Debug.WriteLine(soundOut.GetType().FullName); for (int i = 0; i < BasicIterationCount; i++) { soundOut.Initialize(source); soundOut.Play(); Thread.Sleep(sourceLength + 500); Assert.AreEqual(source.Length, source.Position, "Source is not EOF"); soundOut.Stop(); source.Position = 0; soundOut.Initialize(source); soundOut.Play(); Thread.Sleep(sourceLength + 500); Assert.AreEqual(source.Length, source.Position, "Source is not EOF"); soundOut.Pause(); soundOut.Resume(); Thread.Sleep(10); soundOut.Stop(); source.Position = 0; soundOut.Initialize(source); soundOut.Play(); Thread.Sleep(sourceLength + 1000); Assert.AreEqual(source.Length, source.Position, "Source is not EOF"); Assert.AreEqual(PlaybackState.Stopped, soundOut.PlaybackState); source.Position = 0; soundOut.Play(); Thread.Sleep(sourceLength + 500); Assert.AreEqual(source.Length, source.Position, "Source is not EOF"); } }
void Play_Aux() { float vol = soundOut.Volume * 10; tbar_volume.Value = int.Parse(vol.ToString()); timer_ctime.Interval = 1000; timer_ctime.Start(); timer_ctime.Enabled = true; double t = soundSource.GetLength().TotalSeconds; int i = Convert.ToInt32(t); trackbar_progress.MaxValue = i; label_title.Location = new Point(350); btn_Play.Visible = false; btn_pause.Visible = true; }
private void CanHandleEOFTestInternal(ISoundOut soundOut, IWaveSource source) { int sourceLength = (int)source.GetLength().TotalMilliseconds; for (int i = 0; i < basic_iteration_count; i++) { soundOut.Initialize(source); soundOut.Play(); Thread.Sleep(sourceLength + 500); Assert.AreEqual(source.Length, source.Position, "Source is not EOF"); soundOut.Stop(); source.Position = 0; soundOut.Initialize(source); soundOut.Play(); Thread.Sleep(sourceLength + 500); Assert.AreEqual(source.Length, source.Position, "Source is not EOF"); soundOut.Pause(); soundOut.Resume(); Thread.Sleep(10); soundOut.Stop(); source.Position = 0; soundOut.Initialize(source); soundOut.Play(); Thread.Sleep(sourceLength + 500); Assert.AreEqual(source.Length, source.Position, "Source is not EOF"); source.Position = 0; soundOut.Play(); Thread.Sleep(sourceLength + 500); Assert.AreEqual(source.Length, source.Position, "Source is not EOF"); } }
private void CountTimerDelegate() { double totalMS = iws.GetLength().TotalMilliseconds; while (iws.GetPosition().TotalMilliseconds <= totalMS) { if (isPlaying) { AudioDelegations.PostionChanged?.Invoke(iws.GetPosition()); LyricToken lt; if ((lt = lEnum.Enumerating(iws.GetPosition())) != null) { AudioDelegations.LyricUpdated?.Invoke(lt); } } Thread.Sleep(1000); } isPlaying = false; AudioDelegations.PlayingFinished?.Invoke(); }
public void SetLoopInfo(float begin, float end) { begin *= 1000; end = Mathf.Min(end * 1000, _waveSource.GetLength().Milliseconds); if (begin >= end) { throw new ArgumentOutOfRangeException("begin", "begin should be smaller than end and both should be in the range of audio."); } if (begin <= 0) { throw new ArgumentOutOfRangeException("begin", "begin and end should not be smaller than zero."); } var waveFormat = _waveSource.WaveFormat; _loopBegin = waveFormat.MillisecondsToBytes(begin) / waveFormat.BytesPerSample; _loopEnd = waveFormat.MillisecondsToBytes(end) / waveFormat.BytesPerSample; }
public static SoundSourceInfo FromSoundSource(IWaveSource source) { return new SoundSourceInfo { kHz = source.WaveFormat.SampleRate / 1000, Duration = source.GetLength() }; }
public static SoundSourceInfo FromSoundSource(IWaveSource source) { return(new SoundSourceInfo { kHz = source.WaveFormat.SampleRate / 1000, Duration = source.GetLength() }); }
public TimeSpan getmMWaveSourceLength() { return(mWaveSource.GetLength()); }
private void PlaybackStoppedEventTestInternal(ISoundOut soundOut, IWaveSource source) { for (int i = 0; i < BasicIterationCount; i++) { bool raised = false; soundOut.Stopped += (s, e) => raised = true; //1. wait for the event on end of stream soundOut.Initialize(source); soundOut.Play(); Thread.Sleep((int)(source.GetLength().TotalMilliseconds + 50)); while (soundOut.PlaybackState != PlaybackState.Stopped) Thread.Sleep(10); soundOut.Initialize(source); //the playbackstate may be stopped but event was not fired. initialize will wait until it gets fired. source.Position = 0; Assert.IsTrue(raised); raised = false; //2. event on Stop() soundOut.Play(); Thread.Sleep(50); soundOut.Stop(); Assert.IsTrue(raised); } }
private void CanHandleEOFTestInternal(ISoundOut soundOut, IWaveSource source) { int sourceLength = (int)source.GetLength().TotalMilliseconds; Debug.WriteLine(soundOut.GetType().FullName); for (int i = 0; i < BasicIterationCount; i++) { soundOut.Initialize(source); soundOut.Play(); Thread.Sleep(sourceLength + 500); Assert.AreEqual(source.Length, source.Position, "Source is not EOF"); soundOut.Stop(); source.Position = 0; soundOut.Initialize(source); soundOut.Play(); Thread.Sleep(sourceLength + 500); Assert.AreEqual(source.Length, source.Position, "Source is not EOF"); soundOut.Pause(); soundOut.Resume(); Thread.Sleep(10); soundOut.Stop(); source.Position = 0; soundOut.Initialize(source); soundOut.Play(); Thread.Sleep(sourceLength + 1000); Assert.AreEqual(source.Length, source.Position, "Source is not EOF"); Assert.AreEqual(PlaybackState.Stopped, soundOut.PlaybackState); source.Position = 0; soundOut.Play(); Thread.Sleep(sourceLength + 500); Assert.AreEqual(source.Length, source.Position, "Source is not EOF"); } }
//public PlaybackStoppedDele PlaybackStopped { get; set; } //public PlaybackContiuneDele PlaybackContiune { set; get; } #endregion Properties #region Methods private void InitializePlayback(int Volume = 50, string openMethods = "waveout", string device = "扬声器") { MMDevice mMDevice; device = device.Trim(); openMethods = openMethods.Trim(); if (openMethods.IndexOf("WaveOut") != -1) { IEnumerable <WaveOutDevice> dives = WaveOutDevice.EnumerateDevices(); IEnumerable <WaveOutDevice> divselect = dives.Where(x => x.Name.IndexOf(device) != -1); WaveOutDevice div = null; if (divselect.Count() == 0) { div = dives.FirstOrDefault(); } else if (divselect.Count() == 1) { div = divselect.FirstOrDefault(); } else { Debug.Print("*****输入异常"); div = divselect.FirstOrDefault(); } if (div == null) { throw new NotSupportedException("not exist directsound device"); } _soundOut = new WaveOut() { Device = div, Latency = 100 }; //300延时有个运算溢出,怀疑是其他异常造成的 } else if (openMethods.IndexOf("WasApiOut") != -1) { var enumerator = new MMDeviceEnumerator(); IEnumerable <MMDevice> mMDevices = MMDeviceEnumerator.EnumerateDevices(DataFlow.Render).Where(x => x.DeviceState == DeviceState.Active); IEnumerable <MMDevice> dives = enumerator.EnumAudioEndpoints(DataFlow.All, DeviceState.All).Where(x => x.DeviceState == DeviceState.Active); mMDevices = mMDevices.Join(dives, x => x.FriendlyName, x => x.FriendlyName, (x, y) => x).ToArray(); mMDevice = mMDevices.Where(x => x.FriendlyName.IndexOf(device) != -1).FirstOrDefault(x => x.DeviceState == DeviceState.Active); _soundOut = new WasapiOut() { Device = mMDevice, Latency = 200 }; } else { IEnumerable <DirectSoundDevice> dives = DirectSoundDeviceEnumerator.EnumerateDevices(); var divselect = dives.Where(x => x.Description.IndexOf(device) != -1); DirectSoundDevice div = null; if (divselect.Count() == 0) { div = dives.FirstOrDefault(); } else if (divselect.Count() == 1) { div = divselect.FirstOrDefault(); } else { //Debug.Print("*****输入异常*****"); div = divselect.FirstOrDefault(); } if (div == null) { throw new NotSupportedException("not exist directsound device"); } _soundOut = new DirectSoundOut() { Device = div.Guid, Latency = 100 }; } if (_filePath.LastIndexOf(".mp3") != -1)//流异步读取,此api异步读取flac流在频繁pos时有死锁bug { Stream fs = File.OpenRead(_filePath); _waveSource = new CSCore.Codecs.MP3.Mp3MediafoundationDecoder(fs); } else if (_filePath.LastIndexOf(".flac") != -1) { Stream fs = File.OpenRead(_filePath); _waveSource = new CSCore.Codecs.FLAC.FlacFile(fs, CSCore.Codecs.FLAC.FlacPreScanMode.Default); // _waveSource = new CSCore.Codecs.FLAC.FlacFile(_filePath); } else { _waveSource = CodecFactory.Instance.GetCodec(_filePath); } _soundOut.Initialize(_waveSource); _soundOut.Volume = Volume / 100f; //_soundOut.Stopped += _soundOut_Stopped; _total = _waveSource.GetLength(); }
public void Seek(float percent) { _soundSource.SetPosition(TimeSpan.FromMilliseconds(percent * _soundSource.GetLength().TotalMilliseconds)); }
private void player_Stopped(object sender, PlaybackStoppedEventArgs e) { if (!Changing) { //MessageBox.Show(e.Exception.ToString()); t.Stop(); if (ActualFileIndex == Playlist.Count - 1) ActualFileIndex = 0; else ActualFileIndex++; GetAndFillWithSongInfo(); source = CodecFactory.Instance.GetCodec(Playlist[ActualFileIndex]); if (playerInit) { ttbbPlayPause.Icon = Icon.FromHandle(ToolbarIcons.ic_play_arrow_white_18dp.GetHicon()); ttbbPlayPause.Tooltip = "Wznów odtwarzanie"; player.Initialize(source); source.SetPosition(new TimeSpan(0, 0, 0)); t.Start(); player.Play(); mtbTime.Maximum = Convert.ToInt32(source.GetLength().TotalSeconds); mtbTime.Value = 0; } } }
public Form1() { //MetroMessageBox.Show(this, string.Format("{0} - 1, {1} - 2, {2} - 3", StylesList[1], StylesList[2], StylesList[3])); InitializeComponent(); #region Player Initialization player = GetSoundOut(); playerInit = true; player.Stopped += new EventHandler<PlaybackStoppedEventArgs>(player_Stopped); #endregion LoadFromSettings(); #region Settings Initialization for (int i = 1; i < Enum.GetNames(typeof(MetroColorStyle)).Length; i++) mcbStyles.Items.Add(StylesList[i]); mcbThemes.Items.Add(ThemesList[1]); mcbThemes.Items.Add(ThemesList[2]); mcbThemes.SelectedItem = msm.Theme; mcbStyles.SelectedItem = msm.Style; #endregion #region Taskbar Buttons Add & Delegates ttbbPlayPause.Click += new EventHandler<ThumbnailButtonClickedEventArgs>(ttbbPlayPause_Click); ttbbNext.Click += new EventHandler<ThumbnailButtonClickedEventArgs>(ttbbNext_Click); ttbbPrev.Click += new EventHandler<ThumbnailButtonClickedEventArgs>(ttbbPrev_Click); ttbbForward.Click += new EventHandler<ThumbnailButtonClickedEventArgs>(ttbbForward_Click); ttbbRewind.Click += new EventHandler<ThumbnailButtonClickedEventArgs>(ttbbRewind_Click); TaskbarManager.Instance.ThumbnailToolBars.AddButtons(this.Handle, ttbbPrev, ttbbRewind, ttbbPlayPause, ttbbForward, ttbbNext); #endregion #region Song Initialization foreach (FileInfo fi in (new DirectoryInfo(Path.GetFullPath("TestMusic")).GetFiles())) Playlist.Add(fi.FullName); //TODO: MAKE IT WORKING! /*System.Drawing.Text.PrivateFontCollection pfc = new System.Drawing.Text.PrivateFontCollection(); pfc.AddFontFile(Path.GetFullPath("comfortaa.ttf")); Font = new Font(pfc.Families[0], Font.Size, Font.Style); foreach (Control c in Controls) c.Font = new Font(pfc.Families[0],c.Font.Size, c.Font.Style);*/ GetAndFillWithSongInfo(); source = CodecFactory.Instance.GetCodec(Playlist[ActualFileIndex]); ActualFileIndex = 0; player.Initialize(source); player.Play(); mtbTime.Maximum = Convert.ToInt32(source.GetLength().TotalSeconds); mtbTime.Value = 0; t.Tick += new EventHandler(Tick); t.Start(); #endregion //AddTrackToList(Playlist[0], Playlist[1]); }
private void ttbbPrev_Click(object sender, ThumbnailButtonClickedEventArgs e) { Changing = true; player.Stop(); t.Stop(); if (ActualFileIndex == 0) ActualFileIndex = Playlist.Count - 1; else ActualFileIndex--; GetAndFillWithSongInfo(); source = CodecFactory.Instance.GetCodec(Playlist[ActualFileIndex]); if (playerInit) { ttbbPlayPause.Icon = Icon.FromHandle(ToolbarIcons.ic_play_arrow_white_18dp.GetHicon()); ttbbPlayPause.Tooltip = "Wznów odtwarzanie"; mbtnPlayPause.Image = PlayerControlIcons.ic_pause_grey600_48dp; player.Initialize(source); source.SetPosition(new TimeSpan(0, 0, 0)); t.Start(); player.Play(); mtbTime.Maximum = Convert.ToInt32(source.GetLength().TotalSeconds); mtbTime.Value = 0; } }
private void CanHandleEOFTestInternal(ISoundOut soundOut, IWaveSource source) { int sourceLength = (int)source.GetLength().TotalMilliseconds; for (int i = 0; i < basic_iteration_count; i++) { soundOut.Initialize(source); soundOut.Play(); Thread.Sleep(sourceLength + 500); Assert.AreEqual(source.Length, source.Position, "Source is not EOF"); soundOut.Stop(); source.Position = 0; soundOut.Initialize(source); soundOut.Play(); Thread.Sleep(sourceLength + 500); Assert.AreEqual(source.Length, source.Position, "Source is not EOF"); soundOut.Pause(); soundOut.Resume(); Thread.Sleep(10); soundOut.Stop(); source.Position = 0; soundOut.Initialize(source); soundOut.Play(); Thread.Sleep(sourceLength + 500); Assert.AreEqual(source.Length, source.Position, "Source is not EOF"); source.Position = 0; soundOut.Play(); Thread.Sleep(sourceLength + 500); Assert.AreEqual(source.Length, source.Position, "Source is not EOF"); } }