public void Convert(string inputFile, string outputFile) { using (var outputStream = File.Create(outputFile)) { var channels = AudioSampleReader.ReadChannels(inputFile, out var waveFormat); var oggStream = new OggStream(StaticRandom.Rng.Next()); // Build header var headerBuilder = new HeaderPacketBuilder(); var audioInfo = VorbisInfo.InitVariableBitRate(channels.Count, waveFormat.SampleRate, 0.1f); var infoPacket = headerBuilder.BuildInfoPacket(audioInfo); var commentsPacket = headerBuilder.BuildCommentsPacket(new Comments()); var booksPacket = headerBuilder.BuildBooksPacket(audioInfo); oggStream.PacketIn(infoPacket); oggStream.PacketIn(commentsPacket); oggStream.PacketIn(booksPacket); WriteHeader(oggStream, outputStream); // Store audio var processingState = ProcessingState.Create(audioInfo); var normalizedChannels = Normalize(channels); processingState.WriteData(normalizedChannels, normalizedChannels[0].Length); processingState.WriteEndOfStream(); WriteAudio(oggStream, outputStream, processingState); } }
public void Play(byte track, bool looping) { if (_noAudio == false) { trackid = track.ToString("00"); trackpath = string.Format("{0}/{1}/music/track{2}.ogg", qparam.globalbasedir, qparam.globalgameid, trackid); #if DEBUG Console.WriteLine("DEBUG: track path:{0} ", trackpath); #endif try { _isLooping = looping; if (oggStream != null) { oggStream.Stop(); } oggStream = new OggStream(trackpath, 3); oggStream.IsLooped = looping; oggStream.Play(); oggStream.Volume = _Volume; _noPlayback = false; } catch (Exception e) { Console.WriteLine("Could not find or play {0}", trackpath); _noPlayback = true; //throw; } } }
private void PlatformInitialize(string fileName) { stream = new OggStream(fileName, OnFinishedPlaying); stream.Prepare(); _duration = stream.GetLength(); }
public void Register(string name) { var fileName = string.Format("{0}/{1}/{2}.ogg", _content.RootDirectory, _soundsDirectoryName, name); var stream = new OggStream(fileName); _sounds.Add(name, new Sound(stream, SoundState.Stopped)); }
private static void InitOggStream(int sampleRate, int channels, out OggStream oggStream, out ProcessingState processingState) { // Stores all the static vorbis bitstream settings var info = VorbisInfo.InitVariableBitRate(channels, sampleRate, 0.5f); // set up our packet->stream encoder var serial = new Random().Next(); oggStream = new OggStream(serial); // ========================================================= // HEADER // ========================================================= // Vorbis streams begin with three headers; the initial header (with // most of the codec setup parameters) which is mandated by the Ogg // bitstream spec. The second header holds any comment fields. The // third header holds the bitstream codebook. var comments = new Comments(); comments.AddTag("ARTIST", "TTS"); var infoPacket = HeaderPacketBuilder.BuildInfoPacket(info); var commentsPacket = HeaderPacketBuilder.BuildCommentsPacket(comments); var booksPacket = HeaderPacketBuilder.BuildBooksPacket(info); oggStream.PacketIn(infoPacket); oggStream.PacketIn(commentsPacket); oggStream.PacketIn(booksPacket); // ========================================================= // BODY (Audio Data) // ========================================================= processingState = ProcessingState.Create(info); }
public OggStream GetCue(string name, bool asyncPrecache = false) { OggStream oggStream = (OggStream)null; try { string str = name.Replace(" ^ ", "\\"); bool flag = name.Contains("Ambience"); oggStream = new OggStream(this.MusicAliases[str.ToLower(CultureInfo.InvariantCulture)], 6) { Category = flag ? "Ambience" : "Music", IsLooped = flag }; oggStream.RealName = name; oggStream.Prepare(asyncPrecache); if (name.Contains("Gomez")) { oggStream.LowPass = false; } } catch (Exception ex) { Logger.Log("SoundManager", LogSeverity.Error, ex.Message); } return(oggStream); }
private static void WriteHeader(OggStream oggStream, Stream outputStream) { while (oggStream.PageOut(out var page, true)) { outputStream.Write(page.Header, 0, page.Header.Length); outputStream.Write(page.Body, 0, page.Body.Length); } }
private static void FlushPages(OggStream oggStream, Stream output, bool force) { while (oggStream.PageOut(out OggPage page, force)) { output.Write(page.Header, 0, page.Header.Length); output.Write(page.Body, 0, page.Body.Length); } }
public static void StartStream(string file, float volume = 1.0f) { if (SoundManager.Disabled) { return; } stream = SoundManager.StartStream(file, volume); }
/// <summary> /// VorbisFileWriter that actually writes to a stream /// </summary> /// <param name="outStream">Stream to be written to</param> /// <param name="sampleRate">The sample rate to use</param> /// <param name="channels">The number of channels to use</param> /// <param name="quality">The base quality for Vorbis encoding</param> public VorbisFileWriter(Stream outStream, int sampleRate, int channels, float quality = 0.5f) { this.outStream = outStream; SampleRate = sampleRate; Channels = channels; if (!startBuffers.ContainsKey(sampleRate)) { throw new InvalidOperationException($"Vorbis writer does not support {sampleRate} sample rate."); } // Stores all the static vorbis bitstream settings Console.WriteLine($"Initiating variable bit rate: {channels} channels, {sampleRate} sample rate, {quality} quality"); var info = VorbisInfo.InitVariableBitRate(channels, sampleRate, quality); // set up our packet->stream encoder var serial = MainWindow.MainRandom.Next(); oggStream = new OggStream(serial); // ========================================================= // HEADER // ========================================================= // Vorbis streams begin with three headers; the initial header (with // most of the codec setup parameters) which is mandated by the Ogg // bitstream spec. The second header holds any comment fields. The // third header holds the bitstream codebook. var headerBuilder = new HeaderPacketBuilder(); var comments = new Comments(); var infoPacket = headerBuilder.BuildInfoPacket(info); var commentsPacket = headerBuilder.BuildCommentsPacket(comments); var booksPacket = headerBuilder.BuildBooksPacket(info); oggStream.PacketIn(infoPacket); oggStream.PacketIn(commentsPacket); oggStream.PacketIn(booksPacket); // Flush to force audio data onto its own page per the spec FlushPages(oggStream, outStream, true); // ========================================================= // BODY (Audio Data) // ========================================================= processingState = ProcessingState.Create(info); // Append some zeros at the start so the result has the same length as the input int bufferSize = startBuffers[sampleRate]; float[][] outSamples = new float[channels][]; for (int ch = 0; ch < channels; ch++) { outSamples[ch] = new float[bufferSize]; } processingState.WriteData(outSamples, bufferSize); }
public void CutOff() { if (this.currentCue != null) { this.currentCue.Stop(); this.currentCue.Dispose(); } this.currentCue = (OggStream)null; }
public override void Log(LogEvent eventType, OggStream stream) { var p = streamOffset[stream]; switch (eventType) { case LogEvent.BeginPrepare: Write("(*", 7, p.Y); SetHOffset(stream, 9); break; case LogEvent.EndPrepare: Write(")", p.X, p.Y); SetHOffset(stream, p.X + 1); break; case LogEvent.Play: Write("{", p.X, p.Y); SetHOffset(stream, p.X + 1); break; case LogEvent.Stop: Write("}", p.X, p.Y); SetHOffset(stream, p.X + 1); break; case LogEvent.Pause: Write("[", p.X, p.Y); SetHOffset(stream, p.X + 1); break; case LogEvent.Resume: Write("]", p.X, p.Y); SetHOffset(stream, p.X + 1); break; case LogEvent.Empty: Write(new string(Enumerable.Repeat(' ', Console.BufferWidth - 6).ToArray()), 6, p.Y); SetHOffset(stream, 7); break; case LogEvent.NewPacket: Write(".", p.X, p.Y); SetHOffset(stream, p.X + 1); break; case LogEvent.LastPacket: Write("|", p.X, p.Y); SetHOffset(stream, p.X + 1); break; case LogEvent.BufferUnderrun: Write("!", p.X, p.Y); SetHOffset(stream, p.X + 1); break; } }
public void UpdatePrecache() { if (this.nextCuePrecached || this.strayCues.Count != 0 || OggStreamer.Instance.PendingPrecaches != 0) { return; } this.nextCue = this.SoundManager.GetCue(this.Loop.Name, true); this.nextCuePrecached = true; }
public void SetMusic(string se, bool looping) { float volume = game.settings.musVolume; if (game.settings.mutedMusic) { volume = 0; } if (File.Exists(game.Content.RootDirectory + game.PathSeperator + "Music" + game.PathSeperator + se + ".ogg")) { if (currentMusic == se) { return; } currentMusic = se; if (music != null) { music.Stop(); } } else { currentMusic = ""; music.Stop(); Console.WriteLine("PANIC: MUSIC FILE " + se + " NOT FOUND"); return; } if (se != currentMusic || music == null) { if (music != null) { music.Stop(); music.Dispose(); music = null; } music = new OggStream(game.Content.RootDirectory + game.PathSeperator + "Music" + game.PathSeperator + se + ".ogg"); music.IsLooped = looping; music.Volume = volume; music.Play(); currentMusic = se; } else { if (music.IsFinished()) { music.Stop(); music.Dispose(); music = null; music = new OggStream(game.Content.RootDirectory + game.PathSeperator + "Music" + game.PathSeperator + se + ".ogg"); music.IsLooped = looping; music.Volume = volume; music.Play(); currentMusic = se; } } }
private static void FlushPages(OggStream oggStream, Stream Output, bool Force) { while (oggStream.PageOut(out var page, Force)) { //Console.WriteLine($"Writing page header with {page.Header.Length} bytes of data"); Output.Write(page.Header, 0, page.Header.Length); //Console.WriteLine($"Writing page body with {page.Body.Length} bytes of data"); Output.Write(page.Body, 0, page.Body.Length); } }
void PlatformDispose(bool disposing) { if (stream == null) { return; } stream.Dispose(); stream = null; }
private void PlatformInitialize(string fileName) { // init OpenAL if need be OpenALSoundController.EnsureInitialized(); stream = new OggStream(fileName, OnFinishedPlaying); stream.Prepare(); _duration = stream.GetLength(); }
private static void FlushPages(OggStream oggStream, Stream Output, bool Force) { OggPage page; while (oggStream.PageOut(out page, Force)) { Output.Write(page.Header, 0, page.Header.Length); Output.Write(page.Body, 0, page.Body.Length); } }
public void Dispose() { if (_stream == null) { return; } Stop(); _stream.Dispose(); _stream = null; }
public ActiveAmbienceTrack(AmbienceTrack track, bool activeForDayPhase) { ServiceHelper.InjectServices((object)this); this.volume = 0.0f; this.ActiveForDayPhase = activeForDayPhase; this.OnMuteStateChanged(); this.Track = track; this.cue = this.SoundManager.GetCue(this.Track.Name, false); this.cue.Volume = this.volume; this.cue.Play(); }
void PlatformDispose(bool disposing) { lock (_sourceMutex) { if (stream == null) { return; } stream.Dispose(); stream = null; } }
public override bool TryDecode(IList<Page> pages, IList<Packet> packets, out OggStream stream) { stream = null; //we need a minimum of free packets for id, comment and setup header if (packets.Count < 3) return false; if (!IsVorbisStream(packets[0], packets[1], packets[2])) return false; stream = Decode(pages, packets); return true; }
private void Play() { if (!this.nextCuePrecached) { this.nextCue = this.SoundManager.GetCue(this.Loop.Name, false); } this.nextCue.Volume = this.volume; this.nextCue.Play(); if (this.currentCue != null) { this.strayCues.Add(this.currentCue); } this.currentCue = this.nextCue; this.barsToCount = this.Loop.Duration; this.nextCuePrecached = false; }
private static void WriteAudio( OggStream oggStream, Stream outputStream, ProcessingState processingState) { while (!oggStream.Finished && processingState.PacketOut(out var packet)) { oggStream.PacketIn(packet); while (!oggStream.Finished && oggStream.PageOut(out var page, false)) { outputStream.Write(page.Header, 0, page.Header.Length); outputStream.Write(page.Body, 0, page.Body.Length); } } }
static void FadeVolume(List <OggStream> streams, bool @in, float duration, ConsoleLogger logger) { int index = 0; foreach (var stream in streams) { var from = stream.Volume; var to = @in ? 1f : 0; var speed = @in ? 1 - @from : @from; lock (volumeFades) { CancellationTokenSource token; bool found = volumeFades.TryGetValue(stream, out token); if (found) { token.Cancel(); volumeFades.Remove(stream); } } var sIdx = index++; logger.Write(@in ? "V" : "v", 4, 10 + sIdx); var cts = new CancellationTokenSource(); lock (volumeFades) volumeFades.Add(stream, cts); var sw = Stopwatch.StartNew(); OggStream s = stream; Task.Factory.StartNew(() => { float step; do { step = (float)Math.Min(sw.Elapsed.TotalSeconds / (duration * speed), 1); s.Volume = (to - @from) * step + @from; Thread.Sleep(1000 / 60); } while (step < 1 && !cts.Token.IsCancellationRequested); sw.Stop(); if (!cts.Token.IsCancellationRequested) { lock (volumeFades) volumeFades.Remove(s); logger.Write(" ", 4, 10 + sIdx); } }, cts.Token); } }
public ActiveLoop(Loop loop, bool muted, bool activeForDayPhase, bool dontStart) { ServiceHelper.InjectServices((object)this); this.Muted = muted; this.volume = muted || !activeForDayPhase ? 0.0f : 1f; this.ActiveForDayPhase = activeForDayPhase; this.OnMuteStateChanged(); this.Loop = loop; this.nextCuePrecached = true; this.nextCue = this.SoundManager.GetCue(loop.Name, false); this.barsBeforePlay = (float)this.Loop.Delay; if (dontStart || this.Loop.Delay != 0) { return; } this.FirstPlay(); }
private void ReleaseUnmanagedResources() { if (processingState != null && oggStream != null && outStream != null) { processingState.WriteEndOfStream(); while (!oggStream.Finished && processingState.PacketOut(out var packet)) { oggStream.PacketIn(packet); FlushPages(oggStream, outStream, false); } FlushPages(oggStream, outStream, true); } oggStream = null; processingState = null; }
private void PlaySoundThread(string assetName, bool loop) { string fileName = this.GetAsset(assetName).fileName; string ext = fileName.Substring(fileName.LastIndexOf(@".") + 1); if (ext == "wav") { int channels, bits_per_sample, sample_rate; byte[] data = OpenTKUtils.LoadWave(fileName, out channels, out bits_per_sample, out sample_rate); int buffer = AL.GenBuffer(); int source = AL.GenSource(); AL.BufferData(buffer, OpenTKUtils.WaveFormat(channels, bits_per_sample), data, data.Length, sample_rate); AL.Source(source, ALSourcei.Buffer, buffer); AL.Source(source, ALSourceb.Looping, loop); AL.SourcePlay(source); int state; do { Thread.Sleep(300); AL.GetSource(source, ALGetSourcei.SourceState, out state); } while ((ALSourceState)state == ALSourceState.Playing); AL.SourceStop(source); AL.DeleteSource(source); AL.DeleteBuffer(buffer); } else if (ext == "ogg") { using (var streamer = new OggStreamer()) { OggStream stream = new OggStream(fileName); stream.Prepare(); stream.Play(); } } else { throw new NotImplementedException($"Support for audio extension '{ext}' is not implemented."); } }
public override void Log(LogEvent eventType, OggStream stream) { switch (eventType) { //case LogEvent.BeginPrepare: // Write("(*", 7, p.Y); // SetHOffset(stream, 9); // break; //case LogEvent.EndPrepare: // Write(")", p.X, p.Y); // SetHOffset(stream, p.X + 1); // break; case LogEvent.Play: Utility.Log.Info("Playing music stream."); break; case LogEvent.Stop: Utility.Log.Info("Stopping music stream."); break; case LogEvent.Pause: Utility.Log.Info("Pausing music stream."); break; case LogEvent.Resume: Utility.Log.Info("Resuming music stream."); break; //case LogEvent.Empty: // Write(new string(Enumerable.Repeat(' ', Console.BufferWidth - 6).ToArray()), 6, p.Y); // SetHOffset(stream, 7); // break; //case LogEvent.NewPacket: // Write(".", p.X, p.Y); // SetHOffset(stream, p.X + 1); // break; //case LogEvent.LastPacket: // Write("|", p.X, p.Y); // SetHOffset(stream, p.X + 1); // break; case LogEvent.BufferUnderrun: Utility.Log.Warning("Music stream buffer underrun detected."); break; } }
public void Dispose() { if (this.currentCue != null) { this.currentCue.Stop(); this.currentCue.Dispose(); this.currentCue = (OggStream)null; } this.nextCue.Stop(); this.nextCue.Dispose(); this.nextCue = (OggStream)null; foreach (OggStream oggStream in this.strayCues) { oggStream.Stop(); oggStream.Dispose(); } this.strayCues.Clear(); this.CycleLink = (Action)null; }
public MusicManager() { AudioManager.Initialize(); this.ambient = new OggStream("data/music/ambient1.ogg"); //this.Piano = new SimpleInstrument("data/music/Piano.pp.C4_2.ogg", 261.6); this.Piano = new Piano(); //this.Violin = new SRInstrument("data/music/ViolinGis3-loop.ogg", "data/music/ViolinGis3-decay.ogg", 207.7); //this.Strings = new SimpleInstrument("data/music/StringsC5.ogg", 523.3); //this.Strings = new SRInstrument("data/music/StringsC5-sustain.ogg", "data/music/StringsC5-decay.ogg", 523.3); string filename = "data/music/DarkAndLight.bmc"; //Console.WriteLine("Parsing " + filename); this.composition = new BranchingMusicalComposition(filename); this.ambient.IsLooped = true; this.ambient.Prepare(); this.Parameters = MusicParameters.Default; }
public override bool TryDecode(IList<Page> pages, IList<Packet> packets, out OggStream stream) { stream = new UnknownStream(pages, packets); return true; }
internal bool AddStream(OggStream stream) { lock (iterationMutex) return streams.Add(stream); }
internal bool RemoveStream(OggStream stream) { lock (iterationMutex) return streams.Remove(stream); }
public bool TryReadPacket(out Packet packet) { //Trace.WriteLine ("Entering", "TryReadPacket"); //Trace.Indent(); packet = null; int lastSegment = 0; OggPage page, firstPage; OggStream ostream; if (!this.continuation) { //Trace.WriteLine ("Not a continuation, reading page", "TryReadPacket"); firstPage = page = ReadPage(); if (page == null) { //Trace.Unindent(); //Trace.WriteLine ("Exiting (no packet)", "TryReadPacket"); return false; } if (!this.oggStreams.TryGetValue (page.StreamIndex, out ostream)) { //Trace.WriteLine ("New ogg stream: " + page.StreamIndex, "TryReadPacket"); this.oggStreams[page.StreamIndex] = ostream = new OggStream (ReadPage); } //Trace.WriteLine (String.Format("SI: {0}; G: {1:N0}; S: {2:N0}; SL: {3:N0}", page.StreamIndex, page.GranuleNumber, page.SequenceNumber, page.Segments.Length)); ostream.Enqueue (page); } else { //Trace.WriteLine ("Continuing on page from " + this.lastStreamIndex, "TryReadPacket"); ostream = this.oggStreams[this.lastStreamIndex]; if ((firstPage = page = ostream.Peek()) == null && (firstPage = page = ReadPage()) == null) { //Trace.Unindent(); //Trace.WriteLine ("Exiting (no page)", "TryReadPacket"); return false; } lastSegment = ostream.LastSegment; //Trace.WriteLine (this.lastStreamIndex + " Last segment: " + lastSegment, "TryReadPacket"); } List<byte[]> segments = new List<byte[]>(); int packetLength = 0; bool packetEndFound = false; while (!packetEndFound) { int i; for (i = lastSegment; i < page.Segments.Length; ++i) { int length = page.Segments[i].Length; packetLength += length; segments.Add (page.Segments[i]); //Trace.WriteLine (String.Format ("Segment {0:N0}, length: {1}", i, length), "TryReadPacket"); if (length < 255) { packetEndFound = true; i++; break; } } if (!packetEndFound) { //Trace.WriteLine ("Reached end of page, continuing with another", "TryReadPacket"); ostream.Dequeue(); // used up whole last page OggPage nextPage; while (true) { if ((nextPage = ostream.Peek()) == null && (nextPage = ReadPage()) == null) { this.continuation = true; // Let's try this stream again next call. this.lastStreamIndex = page.StreamIndex; ostream.Enqueue (page); //Trace.Unindent(); //Trace.WriteLine ("Exiting (no page to continue with)", "TryReadPacket"); return false; } if (nextPage.StreamIndex != page.StreamIndex) { OggStream nextStream; if (!this.oggStreams.TryGetValue (page.StreamIndex, out nextStream)) { //Trace.WriteLine ("New ogg stream: " + page.StreamIndex, "TryReadPacket"); this.oggStreams[page.StreamIndex] = nextStream = new OggStream (ReadPage); } nextStream.Enqueue (page); } else { ostream.Enqueue (page); break; } } page = nextPage; lastSegment = 0; } else { ostream.PacketCount++; if (i != page.Segments.Length) { //Trace.WriteLine ("Not done with this page yet (" + i + "/" + page.Segments.Length + ")", "TryReadPacket"); this.continuation = true; this.lastStreamIndex = page.StreamIndex; ostream.LastSegment = i; } else { //Trace.WriteLine ("Finished packet", "TryReadPacket"); ostream.Dequeue(); this.continuation = false; } } } byte[] pdata = AssemblePacket (segments); packet = new OggPacket (page.StreamIndex, ostream.PacketCount - 1, firstPage.GranuleNumber, pdata); //Trace.Unindent(); //Trace.WriteLine ("Exiting", "TryReadPacket"); return true; }
public bool FillBuffer(OggStream stream, int bufferId) { int readSamples; lock (readMutex) { readSamples = stream.Reader.ReadSamples(readSampleBuffer, 0, BufferSize); CastBuffer(readSampleBuffer, castBuffer, readSamples); } AL.BufferData(bufferId, stream.Reader.Channels == 1 ? ALFormat.Mono16 : ALFormat.Stereo16, castBuffer, readSamples * sizeof (short), stream.Reader.SampleRate); ALHelper.Check(); return readSamples != BufferSize; }