public static void PlayGameSound(GameSound sound) { //var isSubscribed = SubscriptionModule.Get().IsSubscribed ?? false; //if (isSubscribed == false)return; if (Prefs.EnableGameSound == false) { return; } Log.InfoFormat("Playing game sound {0}", sound.Name); if (!sound.Src.ToLowerInvariant().EndsWith(".mp3")) { Log.InfoFormat("Playing game sound {0} as wav", sound.Name); PlaySound(sound.Src); return; } Task.Factory.StartNew(() => { try { Log.InfoFormat("Playing game sound {0} as mp3", sound.Name); var mp3Reader = new Mp3FileReader(sound.Src); var stream = new WaveChannel32(mp3Reader) { PadWithZeroes = false }; DisposeObjects.Add(mp3Reader); DisposeObjects.Add(stream); { stream.Position = 0; Mixer.AddMixerInput(stream); lock (Mixer) { if (WaveOut == null) { Log.Info("Starting up wave out"); WaveOut = new WaveOutEvent(); WaveOut.Init(new SampleToWaveProvider(Mixer)); WaveOut.PlaybackStopped += (sender, args) => { WaveOut.Dispose(); WaveOut = null; }; WaveOut.Play(); } } Log.InfoFormat("Initializing game sound {0} as mp3", sound.Name); } } catch (Exception e) { Log.Warn("PlayGameSound Error", e); Program.GameMess.Warning("Cannot play sound {0}, it must be in the format 44100:2", sound.Name); } }); }
/// <summary>Reads sound data from a MP3 file.</summary> /// <param name="fileName">The file name of the MP3 file.</param> /// <returns>The raw sound data.</returns> private static Sound LoadFromFile(string fileName) { using (Mp3FileReader reader = new Mp3FileReader(fileName, wf => new Mp3FrameDecompressor(wf))) { byte[] dataBytes = new byte[reader.Length]; // Convert MP3 to raw 32-bit float n channels PCM. int bytesRead = reader.Read(dataBytes, 0, (int)reader.Length); int sampleCount = bytesRead / (reader.WaveFormat.Channels * sizeof(float)); byte[] newDataBytes = new byte[sampleCount * reader.WaveFormat.Channels * sizeof(short)]; byte[][] buffers = new byte[reader.WaveFormat.Channels][]; for (int i = 0; i < buffers.Length; i++) { buffers[i] = new byte[newDataBytes.Length / buffers.Length]; } // Convert PCM bit depth from 32-bit float to 16-bit integer. using (MemoryStream stream = new MemoryStream(newDataBytes)) using (BinaryWriter writer = new BinaryWriter(stream)) { for (int i = 0; i < bytesRead; i += sizeof(float)) { float sample = BitConverter.ToSingle(dataBytes, i); if (sample < -1.0f) { sample = -1.0f; } if (sample > 1.0f) { sample = 1.0f; } writer.Write((short)(sample * short.MaxValue)); } } // Separated for each channel. for (int i = 0; i < sampleCount; i++) { for (int j = 0; j < buffers.Length; j++) { for (int k = 0; k < sizeof(short); k++) { buffers[j][i * sizeof(short) + k] = newDataBytes[i * sizeof(short) * buffers.Length + sizeof(short) * j + k]; } } } return(new Sound(reader.WaveFormat.SampleRate, sizeof(short) * 8, buffers)); } }
private void music() { try { ms = new MemoryStream(); { new Thread(delegate(object o) { label6.Invoke(new Action(() => label6.Text = "Receiving...")); try { using (var stream = ns) { byte[] buffer = new byte[1024]; int read; while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { var pos = ms.Position; ms.Position = ms.Length; ms.Write(buffer, 0, read); ms.Position = pos; } } } catch (Exception) { } label6.Invoke(new Action(() => label6.Text = "Done!")); }).Start(); while (ms.Length < 65536 * 10) { Thread.Sleep(1000); } ms.Position = 0; trackBar1.Invoke(new Action(() => trackBar1.Enabled = true)); rd = new Mp3FileReader(ms); sound = new WaveOutEvent(); sound.Init(rd); trackBar1.Invoke(new Action(() => trackBar1.Maximum = (int)rd.TotalTime.TotalSeconds)); label3.Invoke(new Action(() => label3.Text = rd.TotalTime.Minutes.ToString() + ":" + rd.TotalTime.Seconds.ToString())); cover.Invoke(new Action(() => cover.Image = Image.FromFile(Environment.CurrentDirectory + @"\images\stream.png"))); sound.Play(); while (sound.PlaybackState == PlaybackState.Playing || sound.PlaybackState == PlaybackState.Paused) { Thread.Sleep(100); } } } catch (ThreadAbortException) { } catch (NullReferenceException) { } catch (Exception) { MessageBox.Show("File is corrupt or missed!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public void Play(string name) { waveOutDevice.Volume = (float)mainWindow.VolumeSlider.Value; TimeSpan duration = new TimeSpan(); if (!firstTime) { Stop(); mainWindow.fileProgress.Value = 0; } if (name.Contains(".mp3")) { mp3Reader = new Mp3FileReader(name); waveOutDevice.Init(mp3Reader); waveOutDevice.Play(); firstTime = false; duration = mp3Reader.TotalTime; ismp3 = true; } if (name.Contains(".wav")) { waveReader = new WaveFileReader(name); waveOutDevice.Init(waveReader); waveOutDevice.Play(); firstTime = false; duration = waveReader.TotalTime; ismp3 = false; } InitTimer(); filepath = name; mainWindow.fileProgress.Maximum = Math.Round(duration.TotalSeconds, 0); double sec; double min = 0; sec = duration.TotalSeconds; if (sec / 60 > 1) { min = Math.Round(sec / 60, 0); sec -= min * 60; if (sec < 0) { sec = 60 + sec; min -= 1; } } string text = min + ":" + Math.Round(sec, 0); mainWindow.maxLabel.Content = text; }
void Slice(string path) { try { using (var reader = new Mp3FileReader(path, builder)) { Mp3Frame frame; // rest secondes from the last file var restOffset = GetLastPart(filestream); if (restOffset == 0) { CreateWriter(); } var timeOfLastCut = 0; var totalTime = reader.TotalTime.TotalSeconds + restOffset; while ((frame = reader.ReadNextFrame()) != null) { //the rest of the file if (overflowTime > 0) { overflowBytes.AddRange(frame.RawData); } else { // not enough time left for a cut if ((totalTime - interval) < timeOfLastCut) { overflowTime = (int)(totalTime - timeOfLastCut); overflowBytes = new List <byte>(); overflowBytes.AddRange(frame.RawData); } else { if (((int)reader.CurrentTime.TotalSeconds + restOffset - timeOfLastCut) >= interval) { // time for a new file filestream?.Dispose(); CreateWriter(); timeOfLastCut = (int)reader.CurrentTime.TotalSeconds + restOffset; //one File Finished progessBar.InvokeIfRequired(() => { progessBar.PerformStep(); }); } filestream.Write(frame.RawData, 0, frame.RawData.Length); } } } } } catch (Exception e) { Console.WriteLine(e.Message); } }
private async void TestRpc() { byte[] bytes = await RpcStreamingService.GetTrackAudio("track1"); var mp3Reader = new Mp3FileReader(new MemoryStream(bytes)); WaveStream wave32 = new WaveChannel32(mp3Reader); WaveOutEvent _waveOutEvent = new WaveOutEvent(); _waveOutEvent.Init(wave32); _waveOutEvent.Play(); }
public bool?SendAudio(Channel voiceChannel, IAudioClient _vClient, CancellationTokenSource cancel, int quality = 20) { bool isFinished = false; var channelCount = _client.GetService <AudioService>().Config.Channels; // Get the number of AudioChannels our AudioService has been configured to use. MemoryStream mp3file; var OutFormat = new WaveFormat(48000, 16, channelCount); // Create a new Output Format, using the spec that Discord will accept, and with the number of channels that our client supports. try { mp3file = new MemoryStream(File.ReadAllBytes(AppDomain.CurrentDomain.BaseDirectory + "topkek.mp3")); } catch (Exception ex) { NonBlockingConsole.WriteLine($"Ok so {AppDomain.CurrentDomain.BaseDirectory} and also {ex.Message} with {ex.StackTrace}"); Console.ReadKey(); throw; } using (var MP3Reader = new Mp3FileReader(mp3file)) // Create a new Disposable MP3FileReader, to read audio from the filePath parameter using (var resampler = new MediaFoundationResampler(MP3Reader, OutFormat)) // Create a Disposable Resampler, which will convert the read MP3 data to PCM, using our Output Format { resampler.ResamplerQuality = quality; // Set the quality of the resampler to 20, a good quality int blockSize = OutFormat.AverageBytesPerSecond / 50; // Establish the size of our AudioBuffer byte[] buffer = new byte[blockSize]; int byteCount; while ((byteCount = resampler.Read(buffer, 0, blockSize)) > 0 && !cancel.IsCancellationRequested) // Read audio into our buffer, and keep a loop open while data is present { try { if (byteCount < blockSize) { // Incomplete Frame for (int i = byteCount; i < blockSize; i++) { buffer[i] = 0; } } if (!cancel.IsCancellationRequested) { _vClient.Send(buffer, 0, blockSize); // Send the buffer to Discord } } catch (OperationCanceledException) { _vClient.Channel.LeaveAudio(); } } } isFinished = true; return(isFinished); }
private int GetMp3FileDuration(string fileName) { try { Mp3FileReader mfr = new Mp3FileReader(fileName); return((int)mfr.TotalTime.TotalSeconds); } catch { return(0); } }
public static AudioClip GetAudio(string path) { // Load MP3 data and convert to WAV var mp3Stream = new MemoryStream(File.ReadAllBytes(path)); var mp3Audio = new Mp3FileReader(mp3Stream); var wav = new Wav(AudioMemStream(mp3Audio).ToArray()); var audioClip = AudioClip.Create(Path.GetFileName(path), wav.SampleCount, 1, wav.Frequency, false); audioClip.SetData(wav.LeftChannel, 0); return(audioClip); }
private void LoadReader(Stream stream) { try { reader = new Mp3FileReader(stream); } catch (System.Exception e) { OnError(e.Message); } }
public static void ConvertMp3ToWav(string path) { //string path = Directory.GetCurrentDirectory() + @"\alarmSound\music.mp3"; using (Mp3FileReader mp3 = new Mp3FileReader(path)) { using (WaveStream pcm = WaveFormatConversionStream.CreatePcmStream(mp3)) { WaveFileWriter.CreateWaveFile(Path.ChangeExtension(path, "wav"), pcm); } } }
public bool Init(string file) { reader = new Mp3FileReader(file); WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(reader); baStream = new BlockAlignReductionStream(pcmStream); waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()); waveOut.Init(baStream); return(true); }
void LoadSong(string path, PlayerControls.ListView.ListViewRow row) { playlist.ForEach(c => c.ActiveRow = row); songProgress.ForEach(item => item.Value = 0); if (path == null) { currentTime.ForEach(item => item.Text = "--:--"); totalTime.ForEach(item => item.Text = "--:--"); remainingTime.ForEach(item => item.Text = "--:--"); title.ForEach(item => item.Text = ""); artist.ForEach(item => item.Text = ""); album.ForEach(item => item.Text = ""); year.ForEach(item => item.Text = ""); albumArt.ForEach(c => c.Image = null); playPause.ForEach(c => c.Checked = false); } else { if (mp3Reader != null) { mp3Reader.Dispose(); } mp3Reader = new Mp3FileReader(path); waveOut.Init(mp3Reader); songProgress.ForEach(item => item.Maximum = (int)mp3Reader.TotalTime.TotalMilliseconds); currentTime.ForEach(item => item.Text = FormatTime(mp3Reader.CurrentTime, mp3Reader.TotalTime)); totalTime.ForEach(item => item.Text = FormatTime(mp3Reader.TotalTime, mp3Reader.TotalTime)); remainingTime.ForEach(item => item.Text = FormatTime(mp3Reader.TotalTime - mp3Reader.CurrentTime, mp3Reader.TotalTime)); TagLib.File f = TagLib.File.Create(path); title.ForEach(item => item.Text = f.Tag.Title); artist.ForEach(item => item.Text = f.Tag.JoinedPerformers.Trim() != "" ? f.Tag.JoinedPerformers : f.Tag.JoinedAlbumArtists); album.ForEach(item => item.Text = f.Tag.Album); year.ForEach(item => item.Text = f.Tag.Year.ToString()); if (f.Tag.Pictures.Length > 0) { var bin = (byte[])(f.Tag.Pictures[0].Data.Data); var img = Image.FromStream(new System.IO.MemoryStream(bin)); //.GetThumbnailImage(100, 100, null, IntPtr.Zero); albumArt.ForEach(item => item.Image = img); } else { albumArt.ForEach(item => item.Image = null); } playPause.ForEach(c => c.Checked = true); waveOut.Play(); } }
void hook_KeyPressed(object sender, KeyPressedEventArgs e) { // HotKey pressed btnSave.PerformClick(); var reader = new Mp3FileReader(saveSoundPath); var waveOut = new WaveOut(); // or WaveOutEvent() waveOut.Init(reader); waveOut.Play(); }
public static void ConvertMp3ToWav(Stream audioFromGoogle, string _outPath_) { using (Mp3FileReader mp3 = new Mp3FileReader(audioFromGoogle)) { using (WaveStream pcm = WaveFormatConversionStream.CreatePcmStream(mp3)) { WaveFileWriter.CreateWaveFile(_outPath_, pcm); pcm.Close(); } } }
public static void OpenMP3(string filename, out AudioSource source) { string outFile; using (var reader = new Mp3FileReader(filename)) { outFile = Path.Combine(Path.GetTempPath(), "conversion.wav"); WaveFileWriter.CreateWaveFile(outFile, reader); } OpenWav(outFile, out source); }
public string Convert(string inputFileName) { var newName = inputFileName.Split('.')[0] + ".wav"; using (var reader = new Mp3FileReader(_fileReader.GetFilePath(inputFileName))) { WaveFileWriter.CreateWaveFile(GetFilePath(newName), reader); } return(newName); }
public void StartStonks(string Way) { var reader = new Mp3FileReader(Way); var waveOut = new WaveOutEvent(); waveOut.Init(reader); waveOut.Play(); Thread.Sleep(reader.TotalTime); waveOut.Stop(); }
private void btnUK_Click(object sender, EventArgs e) { try { var reader = new Mp3FileReader(_ukAudioFile); var waveOut = new WaveOut(); waveOut.Init(reader); waveOut.Play(); } catch { // Ignored } }
public void OpenAudioFile(string filePath) { fileReader = new AudioFileReader(filePath); waveStream = new Mp3FileReader(filePath); Debug.Assert(fileReader.WaveFormat.BitsPerSample != 16, "Only works with 16 bit audio"); var samples = new float[fileReader.Length / 2]; fileReader.Read(samples, 0, samples.Length / 2); LoadAudioItemData(filePath, samples); }
private void cargarArchivo(byte[] cancion) { reader?.Dispose(); reader = null; byte[] mp3Bytes = cancion; var mp3Stream = new MemoryStream(mp3Bytes); reader = new Mp3FileReader(mp3Stream); // DisplayPosition(); }
private WaveStream CreateInputStream(string fileName) { if (!fileName.EndsWith(".mp3")) { throw new InvalidOperationException("Unsupported extension"); } WaveStream mp3Reader = new Mp3FileReader(fileName); return(new WaveChannel32(mp3Reader)); }
/// <summary> /// Creates a WzSoundProperty with the specified name from a file /// </summary> /// <param name="name">The name of the property</param> /// <param name="file">The path to the sound file</param> public WzSoundProperty(string name, string file) { this.name = name; Mp3FileReader reader = new Mp3FileReader(file); this.wavFormat = reader.Mp3WaveFormat; this.len_ms = (int)((double)reader.Length * 1000d / (double)reader.WaveFormat.AverageBytesPerSecond); RebuildHeader(); reader.Dispose(); this.mp3bytes = File.ReadAllBytes(file); }
/// <summary> /// 开始加载资源 /// </summary> /// <param name="fileExtensionName">带后缀的文件名</param> internal static void StartLoadAssets(string fileExtensionName) { //后缀名 string extension = Path.GetExtension(fileExtensionName); //文件名(不带后缀) string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileExtensionName); string songPath = string.Concat(Application.streamingAssetsPath, AssetsControl.AUDIO, fileExtensionName); string lyricPath = string.Concat(Application.streamingAssetsPath, AssetsControl.LYRIC, fileNameWithoutExtension, AssetsControl.LYRICEXTENSION); string moviePath = string.Concat(Application.streamingAssetsPath, AssetsControl.MOVIE, fileNameWithoutExtension, AssetsControl.MOVIEEXTENSION); if (File.Exists(songPath)) { AudioType audioType = AssetsControl.JudgeAudioType(extension); if (audioType == AudioType.MPEG) { //转化为wav string outSongPath = string.Concat(Application.streamingAssetsPath, AssetsControl.AUDIO, fileNameWithoutExtension, AssetsControl.AUDIOMP3TOWAVEXTENSION); using (var reader = new Mp3FileReader(songPath)) { WaveFileWriter.CreateWaveFile(outSongPath, reader); } audioType = AudioType.WAV; //此处更新文件名fileExtensionName string[] songName = ModelManager.Instance.GetLogicDatas.SongsName; for (int i = 0; i < songName.Length; i++) { if (songName[i].Equals(fileExtensionName)) { songName[i] = string.Concat(fileNameWithoutExtension, AssetsControl.AUDIOMP3TOWAVEXTENSION); break; } } File.Delete(songPath); //重定向路径 songPath = outSongPath; } AssetsControl.songRequest = LoadAssetsTools.StartLoadAudioClip(songPath, audioType); } else { Debug.LogError("歌曲文件不存在"); } if (File.Exists(lyricPath)) { AssetsControl.textAssetRequest = LoadAssetsTools.StartLoadTextAsset(lyricPath); } if (File.Exists(moviePath)) { ModelManager.Instance.GetScenesDatas.VideoPlayer.enabled = true; LoadAssetsTools.StartLoadMovie(moviePath, ModelManager.Instance.GetScenesDatas.VideoPlayer); } }
private void loadButton_Click(object sender, EventArgs e) { progressBar1.Value = 0; if (openFileDialog1.ShowDialog() != DialogResult.OK) { return; } output?.Stop(); output?.Dispose(); timer?.Stop(); var fname = openFileDialog1.FileName; if (fname.EndsWith(".mp3")) { mp3FileReader = new Mp3FileReader(fname); pcm = WaveFormatConversionStream.CreatePcmStream(mp3FileReader); } else { MessageBox.Show("File is not mp3!"); return; } granularity = (int)numericUpDown1.Value; textBoxMp3.Text = fname; stream = new BlockAlignReductionStream(pcm); output = new WaveOut(); output.DesiredLatency = 500; output.Init(stream); waveViewer1.WaveStream = stream; trackBar1.Maximum = (int)(stream.TotalTime.TotalSeconds * (1000.0 / granularity)); trackBar1.Value = 0; trackBar2.Maximum = (int)(stream.TotalTime.TotalSeconds * (1000.0 / granularity)); trackBar2.Value = 0; trackBar3.Maximum = (int)(stream.TotalTime.TotalSeconds * (1000.0 / granularity)); trackBar3.Value = trackBar3.Maximum; timer = new Timer(); timer.Interval = (int)(granularity / 2 - 10); timer.Tick += new EventHandler(timer_Tick); textBox1.Text = TimeSpan.FromMilliseconds(0).ToShortForm(); textBox2.Text = TimeSpan.FromMilliseconds(stream.TotalTime.TotalMilliseconds).ToShortForm(); }
private void btnPlay_Click(object sender, RoutedEventArgs e) { if (output != null && output.PlaybackState == PlaybackState.Paused) { output.Play(); btnPlay.IsEnabled = false; btnPause.IsEnabled = true; btnStop.IsEnabled = true; } else { if (txtRuta.Text != null && txtRuta.Text != "") { output = new WaveOutEvent(); output.PlaybackStopped += OnPlaybackStop; reader = new Mp3FileReader(txtRuta.Text); //Configuraciones de WaveOut output.DeviceNumber = cbDispositivos.SelectedIndex; output.NumberOfBuffers = 2; output.DesiredLatency = 150; volumeProvider = new VolumeWaveProvider16(reader); volumeProvider.Volume = (float)sldVolumen.Value; output.Init(volumeProvider); output.Play(); btnStop.IsEnabled = true; btnPause.IsEnabled = true; btnPlay.IsEnabled = false; //00:00:15.465456456 lblDuration.Text = reader.TotalTime.ToString().Substring(0, 8); lblPosition.Text = reader.CurrentTime.ToString().Substring(0, 8); sldPosition.Maximum = reader.TotalTime.TotalSeconds; sldPosition.Value = 0; timer.Start(); } else { //Avisarle al usuario que elija un archivo } } }
public WaveStream CreateMp3OutPut(string fileName) { WaveChannel32 inputStream = null; if (fileName.EndsWith(".mp3")) { WaveStream reader = new Mp3FileReader(fileName); inputStream = new WaveChannel32(reader); } return(inputStream); }
void PlayMusicSting() { //музыку фоном запускаем mp3 ---для этого через NuGet загрузили пакет NAudio.dll(в Сервис) WaveStream reader = new Mp3FileReader(@"G:\C#\Repite Stilman And My Grafic\Resurce_Images\Крик разбойника.mp3"); //WaveStream reader = new Mp3FileReader(@"C:\РУСТ\С#\Resurce_Images\Resurce_Images\Крик разбойника.mp3"); waveOut = new WaveOut(); waveOut.Init(reader); waveOut.Play(); waveOut.PlaybackStopped += WaveOut_PlaybackStopped; }
/// <summary> /// MP3文件转WAV文件 /// </summary> /// <param name="ori_file_path">原MP3文件路径</param> /// <param name="_savePath">转成wav文件后的存储路径</param> public static void MP3_TO_WAV(string ori_file_path, string _savePath) { LogQueue.Add("开始转换:" + ori_file_path); if (File.Exists(ori_file_path)) { LogQueue.Add("正在转换:" + ori_file_path); var stream = File.Open(ori_file_path, FileMode.Open); var reader = new Mp3FileReader(stream); WaveFileWriter.CreateWaveFile(_savePath, reader); } }
public void PlayMp3(Stream audio) { using (Mp3FileReader mp3 = new Mp3FileReader(audio)) using (WaveStream waveFormatConv = WaveFormatConversionStream.CreatePcmStream(mp3)) using (BlockAlignReductionStream blockAlignedStream = new BlockAlignReductionStream(waveFormatConv)) { WaveOut waveOut = new WaveOut(); waveOut.Init(blockAlignedStream); waveOut.Play(); } }
private WaveStream CreateInputStream(string fileName) { WaveChannel32 inputStream; if (fileName.EndsWith(".mp3")) { WaveStream mp3Reader = new Mp3FileReader(fileName); inputStream = new WaveChannel32(mp3Reader); } else { throw new InvalidOperationException("Unsupported extension"); } return inputStream; }
public void RecodeFileToMonoWave(string pathToFile, string outputPathToFile, int targetSampleRate) { using (Mp3FileReader reader = new Mp3FileReader(pathToFile)) { using (var resampler = new MediaFoundationResampler(reader, WaveFormat.CreateIeeeFloatWaveFormat(targetSampleRate, 1))) { WaveFileWriter.CreateWaveFile(outputPathToFile, resampler); } } }