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.
Related
I'm trying to write code to convert a GIF annimation file into a base64 string and then convert it from base 64 string back into an image. The code I've written is for standard image files (i.e. Bitmap, JPEG, GIF). Animated GIFs, however, are different and obviously require a different step-by-step.
Here is the code I've written for converting an image to base64 string:
if (pbTitlePageImage.Image != null)
{
// This is the step-by-step for writing an image to binary.
string Image2BConverted;
using (Bitmap bm = new Bitmap(pbTitlePageImage.Image))
{
using (MemoryStream ms = new MemoryStream())
{
BinaryWriter bw = new BinaryWriter(ms);
bm.Save(ms, ImageFormat.Jpeg);
Image2BConverted = Convert.ToBase64String(ms.ToArray());
GameInfo.TitlePageImage = Image2BConverted;
bw.Close();
ms.Close();
GameInfo.TitlePageImagePresent = true;
ProjectNeedsSaving = true;
}
}
}
And here is the code I've written for converting a base64 string back to an image:
{
byte[] TitlePageImageBuffer = Convert.FromBase64String(GameInfo.TitlePageImage);
MemoryStream memTitlePageImageStream = new MemoryStream(TitlePageImageBuffer, 0, TitlePageImageBuffer.Length);
memTitlePageImageStream.Write(TitlePageImageBuffer, 0, TitlePageImageBuffer.Length);
memTitlePageImageStream.Position = 0;
pbTitlePageImage.Image = Bitmap.FromStream(memTitlePageImageStream, true);
memTitlePageImageStream.Close();
memTitlePageImageStream = null;
TitlePageImageBuffer = null;
}
After converting the base64 string back into an image, it must be loaded into a picturebox. The above code examples will work, but only the first image in the animation chain makes it through and thus is the only part if the animation that appears in the picturebox. I need to write code that will handle the entire animation. Thanks in advance!
I found a way to solve it:
byte[] imageByte = Base64.decodeBase64(imageData.getImageBase64());
new FileOutputStream("image2.gif");
write(imageByte);
close();
I dont know why, but using a FileOutput String i could get a file with the complete animation.
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.
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;
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]
I have four MemoryStreams of data that I want to merge and then open the pdfDocument, without creating a single file.
It's possible to write them down to files and then merge them but that would be bad practice and that can also cause a few issues so I want to avoid that.
However, I can not find a way to merge the MemoryStreams with iText5 for .NET.
Right now, this is how I do it with files:
private static void ConcatenateDocuments()
{
var stream = new MemoryStream();
var readerFrontPage = new PdfReader(Folder + FrontPageName);
var readerDocA = new PdfReader(Folder + docA);
var readerDocB = new PdfReader(Folder + DocB);
var readerAppendix = new PdfReader(Folder + Appendix);
var pdfCopyFields = new PdfCopyFields(stream);
pdfCopyFields.AddDocument(readerFrontPage);
pdfCopyFields.AddDocument(readerDocA );
pdfCopyFields.AddDocument(readerDocB);
pdfCopyFields.AddDocument(readerAppendix);
pdfCopyFields.Close();
SavePdf(stream, FilenameReport);
}
Since I need to remove the use of files, I keep the MemoryStream's as the different parts are built from different resources. So I have references to these memorystreams.
How can this be done?
The error PDF header signature not found can be fixed in this case by setting the stream's Position back to 0. Since you're not getting the error Cannot access a closed Stream I'm assuming that you are already correctly setting the PdfWriter's CloseStream to false.
Below is a full working C# 2010 WinForm app targeting iTextSharp 5.1.1.0 that creates three PDFs in MemoryStreams and combines them. Since I don't have a web server handy I'm writing them to disk.
using System;
using System.Text;
using System.Windows.Forms;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//Create three MemoryStreams
MemoryStream[] streams = { CreateDoc("Page 1"), CreateDoc("Page 2"), CreateDoc("Page 3") };
//I don't have a web server handy so I'm going to write my final MemoryStream to a byte array and then to disk
byte[] bytes;
//Create our final combined MemoryStream
using (MemoryStream finalStream = new MemoryStream())
{
//Create our copy object
PdfCopyFields copy = new PdfCopyFields(finalStream);
//Loop through each MemoryStream
foreach (MemoryStream ms in streams)
{
//Reset the position back to zero
ms.Position = 0;
//Add it to the copy object
copy.AddDocument(new PdfReader(ms));
//Clean up
ms.Dispose();
}
//Close the copy object
copy.Close();
//Get the raw bytes to save to disk
bytes = finalStream.ToArray();
}
//Write out the file to the desktop
string outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Combined.pdf");
using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
fs.Write(bytes, 0, bytes.Length);
}
this.Close();
}
/// <summary>
/// Helper method to create temporary documents
/// </summary>
private MemoryStream CreateDoc(string name)
{
MemoryStream ms = new MemoryStream();
using (Document doc = new Document(PageSize.LETTER))
{
using (PdfWriter writer = PdfWriter.GetInstance(doc, ms))
{
writer.CloseStream = false;
doc.Open();
doc.Add(new Paragraph(name));
doc.Close();
}
}
return ms;
}
}
}
While it seams the PdfReader can not take the stream, the array of the stream works.
var readerFrontPage = new PdfReader(streamFrontPage.ToArray());