ogg to mp3 using NAudio MFT - c#-4.0

Here, I am having a problem while converting ogg file to mp3 format. Reading ogg file is done successfully but while encoding it is throwing exception like,"Exception from HRESULT: 0xC00D3E85". Presently I am working on windows server 2012(64 bit).
public byte[] DecodeOGG(byte[] data,string trgtfilename,int bitrate)
{
byte[] dt = null;
NVorbis.NAudioSupport.VorbisWaveReader vr = null;
using(MemoryStream ms = new MemoryStream(data))
{
ms.Position = 0;
vr = new NVorbis.NAudioSupport.VorbisWaveReader(ms);
}
var samp = new SampleChannel(vr);
var ws = new SampleToWaveProvider16(samp);
MediaFoundationEncoder.EncodeToMp3(ws, trgtfilename, bitrate);
}

You need to call MediaFoundationInterop.Startup() somewhere in your application. NAudio may be updated in the future to call this automatically.

Related

Poi4Xpages - write file to document during postGeneration

as per a suggestion recently received from Stwissel, I am using the following code to convert a file to mime and attach to a notes document during the post generation process of POI4Xpages.
EDITED NEW CODE:
The following code attaches to document, but throws an error: 502 Bad Gateway - The server returned an invalid or incomplete response.
public void saveExcel(Workbook a, Document newDoc) throws NotesException, IOException{
newDoc.replaceItemValue("Form", "Provider");
// Create the stream
Session session = DominoUtils.getCurrentSession();
Stream stream = session.createStream();
// Write the workbook to a ByteArrayOutputStream
ByteArrayOutputStream bos = new ByteArrayOutputStream();
a.write(bos);
// Convert the output stream to an input stream
InputStream is = new ByteArrayInputStream(bos.toByteArray());
stream.setContents(is);
MIMEEntity m = newDoc.createMIMEEntity("body");
MIMEHeader header = m.createHeader("content-disposition");
header.setHeaderVal("Mime attachment");
m.setContentFromBytes(stream, "application/vnd.ms-excel", MIMEEntity.ENC_IDENTITY_BINARY);
m.decodeContent();
newDoc.save(true, true);
}
ORIGINAL CODE:
var stream:NotesStream = session.createStream();
// Do not automatically convert MIME to rich text
session.setConvertMIME(false);
var doc:NotesDocument = database.createDocument();
doc.replaceItemValue("Form", "Provider");
var body:NotesMIMEEntity = doc.createMIMEEntity();
var header:NotesMIMEHeader = body.createHeader("Subject");
header.setHeaderVal("MIME attachment");
if (stream.open("c:\\notes\\data\\abc.xlsx", "binary")) {
if (stream.getBytes() != 0) {
body.setContentFromBytes(stream, "application/vnd.ms-excel",
NotesMIMEEntity.ENC_IDENTITY_BINARY);
} else requestScope.status = "File was not found.";
} else requestScope.status = "Could not open file.";
stream.close();
doc.save(true, true);
// Restore conversion
session.setConvertMIME(true);
However, this code is only attaching a file which is already stored on the server's local directory. How can I get this code to take the POI fileOutputStream and attach that?
It's a mix of what what Knut and I've commented about. The important part is that you'll use the write() method to pass the workbook data to an output stream.
// Create the stream
Stream stream = session.createStream();
// Write the workbook (you haven't clarified) to a ByteArrayOutputStream
ByteArrayOutputStream bos = new ByteArrayOutputStream();
workbook.write(bos);
// Convert the output stream to an input stream
InputStream is = new ByteArrayInputStream(bos.toByteArray());
stream.setContents(is);

Set volume to mp3 stream using NAudio

Here in this code,
I am using NAudio and Lame to convert wav file to mp3 stream and I am getting mp3 stream output without any issues. But apart from this I also want to set volume to the final mp3 stream. Any help is greatly appreciated.
public byte[] ConvertWavToMP3(byte[] bt, uint bitrate)
{
MemoryStream ms = new MemoryStream(bt);
ms.Seek(0, SeekOrigin.Begin);
var ws = new WaveFileReader(ms);
byte[] wavdata = null;
using (MemoryStream wavstrm = new MemoryStream())
using (WaveFileWriter wavwri = new WaveFileWriter(wavstrm, ws.WaveFormat))
{
ws.CopyTo(wavwri);
wavdata = wavstrm.ToArray();
}
WaveLib.WaveFormat fmt = new WaveLib.WaveFormat(ws.WaveFormat.SampleRate, ws.WaveFormat.BitsPerSample, ws.WaveFormat.Channels);
Yeti.Lame.BE_CONFIG beconf = new Yeti.Lame.BE_CONFIG(fmt, bitrate);
using (MemoryStream mp3strm = new MemoryStream())
using (Mp3Writer mp3wri = new Mp3Writer(mp3strm, fmt, beconf))
{
mp3wri.Write(wavdata, 0, wavdata.Length);
byte[] mp3data = mp3strm.ToArray();
return mp3data;
}
}
You can use AudioFileReader which will give you a Volume property you can adjust (1.0 is full scale). It will also turn the audio into an ISampleProvider with IEEE float samples, but I think LAME accepts IEEE float, otherwise use SampleToWaveProvider16 to get back down to 16 bit integer samples.

How to get isolated storage image as stream?

I have very uncommon problem. firstly let me tell you that i want to build a WP8 apps about images. I have some images stored in the project solution and using those for the apps and it is working fine.
i am using one
public Stream ImageStream
{
get
{
return this.imageStream;
}
set
{
this.imageStream = value;
}
}
Now for the project solution images this Image stream i am calling like this
StreamResourceInfo imageRes = Application.GetResourceStream(new Uri("WindowsPhone;component/Images/Image1.jpg", UriKind.Relative));
this.ImageStream = imageRes.Stream;
Now the problem begins if I try to use any image from media library. I can store the file into Isolated storage and from their I can access the file. What I am doing is
using (IsolatedStorageFile Iso = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var stream = new IsolatedStorageFileStream(strFileName, FileMode.Open, FileAccess.Read, Iso))
{
IsolatedStorageFileStream fileStream = Iso.OpenFile(strFileName, FileMode.Open, FileAccess.Read);
data = new byte[stream.Length];
// Read the entire file and then close it
stream.Read(data, 0, data.Length);
stream.Close();
}
}
MemoryStream ms = new MemoryStream(data);
BitmapImage bi = new BitmapImage();
// Set bitmap source to memory stream
bi.SetSource(ms);
However i can use the image file and can show but you can see it is a bit map image, and as it is in isolated storage I can not use
StreamResourceInfo imageRes ...
this.ImageStream = ...
Any help how can I use this.ImageSteam Properties? any other ideas will be welcome. I am actually beginner in WP8 programming
Or Let me ask you a simple Question how can I read a image which is in isolatedstorage to StreamResourceInfo ?
If I can do that my problem is solved. please help me.
*Save Image to Isolated Storage: *
String tempJPEG = "logo.jpg";
// Create virtual store and file stream. Check for duplicate tempJPEG files.
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(tempJPEG))
{
myIsolatedStorage.DeleteFile(tempJPEG);
}
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(tempJPEG);
StreamResourceInfo sri = null;
Uri uri = new Uri(tempJPEG, UriKind.Relative);
sri = Application.GetResourceStream(uri);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(sri.Stream);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Encode WriteableBitmap object to a JPEG stream.
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
//wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
}
Happy Coding...
why execute a stream copy ?
http://www.windowsphonegeek.com/tips/All-about-WP7-Isolated-Storage---Read-and-Save-Images
try something like
BitmapImage bi = new BitmapImage();
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("logo.jpg", FileMode.Open, FileAccess.Read))
{
bi.SetSource(fileStream);
this.img.Height = bi.PixelHeight;
this.img.Width = bi.PixelWidth;
}
}
this.img.Source = bi;

Create a copy of an InputStream from an HttpURLConnection so it can be used twice

I used this question
How do I convert an InputStream to a String in Java?
to convert an InputStream to a String with this code:
public static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
My inputstream comes from an HttpURLConnection InputStream, and when I do my conversion to String, the inputstream changes and I cannot longer use it. This is the error that I get:
Premature end of file.' SOAP
What can I do to keep my inputstream, when I convert it to string with the proper information?.
Speciffically this is the information that changes:
inCache = true (before false)
keepAliveConnections = 4 (before 5)
keepingAlive = false (before true)
poster = null (before it was PosterOutputStream object with values)
Thank you.
If you pass your input stream into scanner or read its data in any other way. you actually consuming its data and there will be no available data in that stream anymore.
you may need to create a new input stream with same data and use it instead of the original one. for example:
ByteArrayOutputStream into = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
// inputStream is your original stream.
for (int n; 0 < (n = inputStream.read(buf));) {
into.write(buf, 0, n);
}
into.close();
byte[] data = into.toByteArray();
//This is your data in string format.
String stringData = new String(data, "UTF-8"); // Or whatever encoding
//This is the new stream that you can pass it to other code and use its data.
ByteArrayInputStream newStream = new ByteArrayInputStream(data);
The scanner reads till the end of the stream and closes it. So it will not be available further. Use PushbackInputStream as a wrapper to your input stream and use the unread() method.
Try to Use Apache Utilities.
In my preset project, I have done the same thing
InputStream xml = connection.getInputStream();
String responseData = IOUtils.toString(xml);
You can get IOUtils from Apache [import org.apache.commons.io.IOUtils]

audio playback error

I'm trying to record an audio file and play it, but I'm getting en error: Locator does not reference a valid media file. What am I missing?
here is my code of saving audio file:
//Stop recording, capture data from the OutputStream,
//close the OutputStream and player.
_rcontrol.commit();
_data = _output.toByteArray();
_output.close();
_player.close();
isRecording = 0;
try {
FileConnection fc = (FileConnection)Connector.open("file:///store/home/user/Audio.mp3");
// If no exception is thrown, then the URI is valid, but the file may or may not exist.
if (!fc.exists()) {
fc.create(); // create the file if it doesn't exist
}
OutputStream outStream = fc.openOutputStream();
outStream.write(_data);
outStream.close();
fc.close();
System.out.println("audio size: "+_data.length);
I can see in log, that my audio file has some length (about 5000 after 3-4 seconds of recording)
here is my code where i'm trying to play it:
FileConnection fc = (FileConnection)Connector.open("file:///store/home/user/Audio.mp3");
// If no exception is thrown, then the URI is valid, but the file may or may not exist.
if (fc.exists()) {
_player = Manager.createPlayer("file:///store/home/user/Audio.mp3");
_player.realize();
_player.prefetch();
if (_player.getMediaTime() == _player.TIME_UNKNOWN) {
System.out.println("zero audio doration");
}
else {
System.out.println("audio doration: "+_player.getMediaTime());
}
_player.start();
}
fc.close();

Resources