Stream Ogg File - c#

Does anyone know how to stream Ogg files without fully downloading them first over a Socket(in byte[] format).
I am trying to create a music streaming application and I managed to do it with MP3's but I understand there's licensing issues invovled after certain limit hence why I want to use OGG(Vorbis). I maanged to find this C# Vorbis Wrapper but no documentation, and I cannot figure out how to get a byte[] stream to play.
I have tried the following
var rawData = File.ReadAllBytes(#"SoundFile.ogg");
var enc = new OggVorbisEncodedStream(rawData);
var sp = new SoundPlayer(enc);
sp.Play();
But an exception gets thrown showing that the Wav file header is incorrect. I understand SoundPlayer is used for only playing .wav files? Does anybody know how to stream a OGG file?

The wrapper is a very thin one, it directly calls the native ogg codec functions. Look for the docs of ov_read to see what you get back from OggVorbisEncodedStream.Read(). Raw PCM would be my guess. The wrapper doesn't attempt any kind of format conversion.
Yes, SoundPlayer won't work here, it requires wav and can't stream. You'll need a player that can take chunks of PCM as an input. Not sure what does that, the NAudio project is usually good for stuff like this.

string filePath = "License.lic";
using (var stream = new StreamReader(filePath))

Related

UWP Media Playback with dynamic source

i hope the title does not confuse you.
First: i am working with UWP c#.
I receive media-information (video and audio) in form of bytes from a remote device. Now i need to play them while new information is incoming.
For now, i have a FileStream, which writes the data everytime i receive the bytes. That works. But when i want to play this file, it just shows the media, that was written at the moment i call MediaElement.Play()
Is there any opportunity, the MediaElement (or another media player) keeps reading from the file or from the incomming bytes? Any Idea?
I'm afraid that this is not possible.
You have to implement IRandomAccessStream as wrapper for your FileStream and pass it to MediaSource.CreateFromStream(IRandomAccessStream, string) function.
Here is an example for implementing IRandomAccessStream on top of MemoryStream

Save WPF BitmapSources as h264 encoded video directly from Memory

Currently I am utilizing a List-variable to store BitmapSources provided by a camera and save them as an AVI file with the help of SharpAvi. In a second step I then encode the saved file via Nrecos ffmpeg wrapper to decrease file size. Finally I delete the original AVI file and only keep the encoded one.
To me this seems poorly designed and might cause harmful write-cycles to the SSD the application is running on (I'll probably create up to a TB a day in unencoded video), which is why I want to change it to a more integrated solution utilizing the PC's RAM.
SharpAvi as well as Nreco however rely on creating and reading actual files.
Nreco does have the ConvertLiveMedia method that accepts a stream - however in my experiments it simply did not create a file while giving me no error warnings.
Ok I think I solved it:
I changed the SharpAvi code so that the AviWriter has an additional constructor accepting a MemoryStream instead of just a string. This MemoryStream is then passed to the BinaryWriter and no FileStream is created.
Also the close Method had to be changed so that the MemoryStream stays alive even when the BinaryWriter is closed.fileWriter.Closeis replaced with
if (fileWriter.BaseStream is MemoryStream)
fileWriter.Flush();
else
fileWriter.Close();
This leaves me with a usable MemoryStream in my main application.
memstream.Position = 0; //crucial or otherwise ffmpeg will not work
var task = nrecoconverter.ConvertLiveMedia(memstream, "avi", filepath, "avi", settings);
task.Start();
task.Wait();
Edit: SharpAvi has officially been changed on github to allow the use of Streams now.

get image from video stream in C#

I am trying to get image from a stream (MemoryStream to be more precise). I can not find anything from Microsoft that can solve my problem.
I am getting my streams from SQL so if there is some way to get an image from there, it will be OK.
I have checked ffmpeg and the problem is that I need to save the video files. The files can reach up to 2GB and if there is a way not writing to the disk it will be helpful. If there is a way to read only the first 10MB or other limited size and read the image from it, that can also be a solution.
Video feed might be as simple as raw uncompressed video frames side by side to more complex multiplexed file format compatible chunk of data, e.g. .MP4 file. While the former case might be pretty simple, the latter requires you to demultiplex the file, seek within the stream, start decoding, possibly skip a few frames, then grab the frame of interest. The point is that it might be not as simple as it seems.
Video processing APIs in Windows are DirectShow, Media Foundation. With DirectShow it is possible to create a custom data source on top of SQL backed data stream and stream from there fetching DB data on demand, using API interfaces components (stock and third party) to do the rest of the task.
It is possible to capture frames with free VideoConverter for .NET that actually is a wrapper to FFMpeg tool. The idea is using live streaming capabilities (to C# Stream) of VideoConverter for special FFMpeg format "rawvideo" that actually is bitmap stream that can be processed by C# program, something like that:
var videoConv = new FFMpegConverter();
var ffMpegTask = videoConv.ConvertLiveMedia(
"input.mp4",
null, // autodetect live stream format
rawBmpOutputStream, // this is your special stream that will capture bitmaps
"rawvideo",
new ConvertSettings() {
VideoFrameSize = "320x200", // lets resize to exact frame size
CustomOutputArgs = " -pix_fmt bgr24 ", // windows bitmap pixel format
VideoFrameRate = 5, // lets consume 5 frames per second
MaxDuration = 5 // lets consume live stream for first 5 seconds
});
VideoConverter can read live streams from another .NET Stream (if input format can be used with live stream conversion).

How to read using C++ (C#) sound stream sent by flash?

I need to read sound stream sent by flash audio in my C++ application (C++ is not a real limitation, it may be C# or any other desktop language).
Now flash app sends audio to another flash app but I need to receive the same audio by desktop application.
So, is there a standard or best way how to do it?
Thank you for your answers.
How is the sound actually sent? Via the network?
Edit: You'd be either capturing the audio from an HTTP stream, or an RTMP stream. Run Wireshark to find out, but I suspect you're doing something slightly shady...
You could try using the sound system from the Gnash project.
So basically you want to connect to RTMP sound stream from flash media server from an arbitrary non-flash application? Have you taken a look at http://en.wikipedia.org/wiki/Real_Time_Messaging_Protocol ?
Unfortunately, Adobe IS relatively proprietary (hence the apple-adobe wars happening lately), but for several languages, there are projects to help out with RTMP.
WebOrb is commercial, for .NET, Java, PHP:
http://www.themidnightcoders.com/products.html
FluorineFX is open source for .NET only:
http://www.fluorinefx.com/
I haven't used either myself for RTMP, but I have used FluorineFX to connect to a flash remoting (AMF) gateway. I imagine it may do what you need for receiving the audio stream from a .NET-enabled client.
Getting the frames, frame rate and other attributes of video clip
If you have experience with writing applications in Microsoft DirectShow Editing Services (codename Dexter), this will sound very familiar to you. In the Windows environment, traditionally capturing still frames has been done using C++ and Dexter Type Library to access DirectShow COM objects. To do this in .NET Framework, you can make an Interop assembly of DexterLib which is listed under COM References in VS 2005. However it takes you a good amount of work to figure out how to convert your code from C++ to C# .NET. The problem occurs when you need to pass in a pointer reference as an argument to a native function, CLR does not directly support pointers as the memory position can change after each garbage collection cycle. You can find many articles on how to use DirectShow on the CodeProject or other places and we try to keep it simple. Here our goal is to convert a video file into an array of Bitmaps and I tried to keep this as short as possible, of course you can write your own code to get the Bitmaps out of a live stream and buffer them shortly before you send them.
Basically we have two option for using the DirectShow for converting our video file to frames in .NET:
Edit the Interop assembly and change the type references from pointer to C# .NET types.
Use pointers with unsafe keyword.
We chose the unsafe (read fast) method. It means that we extract our frames outside of .NET managed scope. It is important to mention that managed does not always mean better and unsafe does not really mean unsafe!
MediaDetClass mediaClass = new MediaDetClass();
_AMMediaType mediaType;
... //load the video file
int outputStreams = mediaClass.OutputStreams;
outFrameRate=0.0;
for (int i = 0; i < outputStreams; i++)
{
mediaClass.CurrentStream = i;
try{
//If it can the get the framerate, it's enough,
//we accept the video file otherwise it throws an exception here
outFrameRate = mediaClass.FrameRate;
.......
//get the attributes here
.....
}catch
{ // Not a valid meddia type? go to the next outputstream }
}
// No frame rate?
if (outFrameRate==0.0)
throw new NotSupportedException( " The program is unable" +
" to read the video file.");
// we have a framerate? move on...
...
//Create an array to hold Bitmaps and intilize
//other objects to store information...
unsafe {
...
// create a byte pointer to store the BitmapBits
...
while (currentStreamPos < endPosition)
{
mediaClass.GetBitmapBits(currentStreamPos, ref bufferSize,
ref *ptrRefFramesBuffer,
outClipSize.Width, outClipSize.Height);
...
//add frame Bitmap to the frameArray
...
}
}
...
Transfer extracted data over HTTP
So far we have converted our video to an array of Bitmap frames. The next step is to transfer our frames over HTTP all the way to the client�s browser. It would be nice if we could just send our Bitmap bits down to the client but we cannot. HTTP is designed to transport text characters which mean your browser only reads characters that are defined in the HTML page character set. Anything else out of this encoding cannot be directly displayed.
To accomplish this step, we use Base64 encoding to convert our Bitmap to ASCII characters. Traditionally, Base64 encoding has been used to embed objects in emails. Almost all modern browsers including Gecko browsers, Opera, Safari, and KDE (not IE!) support data: URI scheme standard to display Base64 encoded images. Great! Now, we have our frames ready to be transferred over HTTP.
System.IO.MemoryStream memory = new System.IO.MemoryStream();
while (currentStreamPos < endPosition)
{
...
// Save the Bitmpas somewhere in the (managed) memory
vdeoBitmaps.Save(memory, System.Drawing.Imaging.ImageFormat.Jpeg);
//Convert it to Base64
strFrameArray[frameCount] = System.Convert.ToBase64String(memory.ToArray());
//Get ready for the next one
memory.Seek(0, System.IO.SeekOrigin.Begin);
}
memory.Close();
...
But we cannot just send out the encoded frames as a giant string. We create an XML document that holds our frames and other information about the video and then send it to the client. This way the browser can receive our frames as a DOM XML object and easily navigate through them. Just imagine how easy it is to edit a video that is stored in XML format:
14.9850224700412
{Width=160, Height=120}
6.4731334
/9j/4AAQSkZJRgABAQEAYAB....
....
This format also has its own drawbacks. The videos that are converted to Base64 encoded XML files are somewhere between 10% (mostly AVI files) to 300 % or more (some WMV files) bigger than their binary equivalent.
If you are using an XML file, you even don't need a web server , you can open the HTML from a local directory and it should work! I included an executable in the article's download file that can convert your video file to XML document which later can be shown in the browser. However using big files and high resolution videos is not a good idea!
OK, now we can send out our �Base64 encoded video� XML document as we would do with any other type of XML files. Who says XML files always have to be boring record sets anyway

Play PCM data in .NET Framework 2?

I have a stream of u-Law compressed PCM data I am extracting from a Camera, I need to play this out the speakers? Anybody know how? I've tried decoding the u-Law into normal WAV Data and then use SoundPlayer but it never seems to work! Always SoundPlayer only supports PCM Data?
I know the sounds ok, because I have saved it to a file (using a custom createWavHeader method) and iTunes can play it.
Windows comes with an ACM codec to convert u-law to PCM. You can use NAudio and use the WaveFileReader and the WaveFormatConversionStream to get a PCM stream you can play easily.
Similarly, there is a freeware library lizPlay providing PCM playing capabilities. Worth considering as developers of lizPlay pay special attention to ensure there is a version that is free of patent infringement issues.

Categories