audio playback error - audio

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();

Related

Input output stream not working in Web Forms function

Can someone tell me why I keep getting a read and write timeout on this function? I have this as a code behind function on click even from a button. Everything as far as the data looks good until I get to the stream section and it still steps through, but when I check the Stream object contents after stepping into that object it states Read Timeout/Write Timeout: System invalid Operation Exception.
protected void SubmitToDB_Click(object sender, EventArgs e)
{
if (FileUploader.HasFile)
{
try
{
if (SectionDropDownList.SelectedValue != null)
{
if (TemplateDropDownList.SelectedValue != null)
{
// This gets the full file path on the client's machine ie: c:\test\myfile.txt
string strFilePath = FileUploader.PostedFile.FileName;
//use the System.IO Path.GetFileName method to get specifics about the file without needing to parse the path as a string
string strFileName = Path.GetFileName(strFilePath);
Int32 intFileSize = FileUploader.PostedFile.ContentLength;
string strContentType = FileUploader.PostedFile.ContentType;
//Convert the uploaded file to a byte stream to save to your database. This could be a database table field of type Image in SQL Server
Stream strmStream = FileUploader.PostedFile.InputStream;
Int32 intFileLength = (Int32)strmStream.Length;
byte[] bytUpfile = new byte[intFileLength + 1];
strmStream.Read(bytUpfile, 0, intFileLength);
strmStream.Close();
saveFileToDb(strFileName, intFileSize, strContentType, bytUpfile); // or use FileUploader.SaveAs(Server.MapPath(".") + "filename") to save to the server's filesystem.
lblUploadResult.Text = "Upload Success. File was uploaded and saved to the database.";
}
}
}
catch (Exception err)
{
lblUploadResult.Text = "The file was not updloaded because the following error happened: " + err.ToString();
}
}
else
{
lblUploadResult.Text = "No File Uploaded because none was selected.";
}
}
Try something like this:
using (var fileStream = FileUploader.PostedFile.InputStream)
{
using (var reader = new BinaryReader(fileStream))
{
byte[] bytUpfile = reader.ReadBytes((Int32)fileStream.Length);
// SAVE TO DB...
}
}

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);

ogg to mp3 using NAudio MFT

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.

How to get an existing video thumbnail image from MonoTouch?

I'm trying to get a thumbnail image for a video that I've just chosen (or recorded) via the UIImagePickerController. In my picker's FinishedPickingMedia method, I get what I believe to be the path to the video file and use it to save the recording to album. The newly recorded video does indeed appear in my album. Now to get the thumbnail…
I've tried using the ALAssetsLibrary in a couple ways. First, I've enumerated all the videos and tried to find a match from the asset's UtiToUrlDictionary.Values[0] value, which reveals its file path. No entries matched the path I obtained from the FinishedPickingMedia method's mediaUrlKey.
My second attempt was to use the ALAssetsLibrary's AssetForUrl() method. Again, I tried my FinishedPickingMedia method's mediaUrlKey, but there was no match.
The UIImagePickerController -> FinishedPickingMedia -> mediaUrlKey returns a path of:
file://localhost/private/var/mobile/Applications/73037738-C060-4DE6-A1CA-698E6BE083F2/tmp//trim.iRBwWw.MOV
After painful digging and inspecting every video in my library, it the same video's path from the ALAssetsLibrary is:
assets-library://asset/asset.MOV?id=B073FCF6-83ED-436B-AFD8-42D0A6C70FC6&ext=MOV
Why are the video paths different between UIIMagePickerController and ALAssetsLibrary? How can I get ALAssetsLibrary to return the same video picked from UIImagePickerController?
[code for the picker]
public override void FinishedPickingMedia (UIImagePickerController picker, NSDictionary info)
{
var mediaUrlKey = new NSString("UIImagePickerControllerMediaURL");
var mediaPath = (NSUrl) info.ObjectForKey(mediaUrlKey);
if( recordView.RecordVideo )
{
if(mediaPath != null)
{
if(UIVideo.IsCompatibleWithSavedPhotosAlbum(mediaPath.Path))
{
UIVideo.SaveToPhotosAlbum(mediaPath.Path, SaveToPhotosAlbumResults);
}
else
{
using (var alert = new UIAlertView("Problem Encountered",
"Unable to save this recording.", null, "Ok!", null))
{
alert.Show();
}
}
}
}
else
{
recordView.VideoFileLocation = mediaPath;
//ALAssetsLibrary library = new ALAssetsLibrary();
//library.AssetForUrl( mediaPath, GetAssetResult, GetAssetError );
}
recordView.VideoFileLocation = mediaPath;
Console.WriteLine("***" + recordView.VideoFileLocation.ToString()+ "***");
recordView.ShowUploadButton();
recordView.SetThumbnailImage();
picker.DismissModalViewControllerAnimated(true);
}
Thank you
I think may be it is too late but the following code work as of now
public static UIImage GenerateImage(NSUrl videoUrl)
{
var asset = AVAsset.FromUrl(videoUrl);
var imageGenerator = AVAssetImageGenerator.FromAsset(asset);
imageGenerator.AppliesPreferredTrackTransform = true;
var actualTime = asset.Duration;
CoreMedia.CMTime cmTime = new CoreMedia.CMTime(1, 60);
NSError error;
var imageRef = imageGenerator.CopyCGImageAtTime(cmTime, out actualTime, out error);
if (imageRef == null)
return null;
var image = UIImage.FromImage(imageRef);
return image;
}
I think the section Can I Get To The Original File Representing This Image on the Disk in this question can help you.
This is how you can get a thumbnail within the picker delegate:
NSUrl data = new NSUrl(info.ObjectForKey(new NSString("UIImagePickerControllerMediaURL")).ToString());
//get the video thumbnail
MPMoviePlayerController movie = new MPMoviePlayerController(data);
movie.Stop();
UIImage videoThumbnail = movie.ThumbnailImageAt(0.0,MPMovieTimeOption.NearestKeyFrame);
movie.Stop();

GDI+ Generic Error

When my images are being loaded from my database on my web server, I see the following error:
A generic error occurred in GDI+. at
System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder,
EncoderParameters encoderParams) at
System.Drawing.Image.Save(Stream stream, ImageFormat format) at
MyWeb.Helpers.ImageHandler.ProcessRequest(HttpContext context)
All my code is attempting to do is load the image, can anybody take a look and let me know what I'm doing wrong?
Note - This works if I test it on my local machine, but not when I deploy it to my web server.
public void ProcessRequest(HttpContext context)
{
context.Response.Clear();
if (!String.IsNullOrEmpty(context.Request.QueryString["imageid"]))
{
int imageID = Convert.ToInt32(context.Request.QueryString["imageid"]);
int isThumbnail = Convert.ToInt32(context.Request.QueryString["thumbnail"]);
// Retrieve this image from the database
Image image = GetImage(imageID);
// Make it a thumbmail if requested
if (isThumbnail == 1)
{
Image.GetThumbnailImageAbort myCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
image = image.GetThumbnailImage(200, 200, myCallback, IntPtr.Zero);
}
context.Response.ContentType = "image/png";
// Save the image to the OutputStream
image.Save(context.Response.OutputStream, ImageFormat.Png);
}
else
{
context.Response.ContentType = "text/html";
context.Response.Write("<p>Error: Image ID is not valid - image may have been deleted from the database.</p>");
}
}
The error occurs on the line:
image.Save(context.Response.OutputStream, ImageFormat.Png);
UPDATE
I've changed my code to this, bit the issue still happens:
var db = new MyWebEntities();
var screenshotData = (from screenshots in db.screenshots
where screenshots.id == imageID
select new ImageModel
{
ID = screenshots.id,
Language = screenshots.language,
ScreenshotByte = screenshots.screen_shot,
ProjectID = screenshots.projects_ID
});
foreach (ImageModel info in screenshotData)
{
using (MemoryStream ms = new MemoryStream(info.ScreenshotByte))
{
Image image = Image.FromStream(ms);
// Make it a thumbmail if requested
if (isThumbnail == 1)
{
Image.GetThumbnailImageAbort myCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
image = image.GetThumbnailImage(200, 200, myCallback, IntPtr.Zero);
}
context.Response.ContentType = "image/png";
// Save the image to the OutputStream
image.Save(context.Response.OutputStream, ImageFormat.Png);
} }
Thanks.
Probably for the same reason that this guy was having problems - because the for a lifetime of an Image constructed from a Stream, the stream must not be destroyed.
So if your GetImage function constructs the returned image from a stream (e.g. a MemoryStream) and then closes the stream before returning the image then the above will fail. My guess is that your GetImage looks a tad like this:
Image GetImage(int id)
{
byte[] data = // Get data from database
using (MemoryStream stream = new MemoryStream(data))
{
return Image.FromStream(data);
}
}
If this is the case then try having GetImage return the MemoryStream (or possibly the byte array) directrly so that you can create the Image instance in your ProcessRequest method and dispose of the stream only when the processing of that image has completed.
This is mentioned in the documentation but its kind of in the small print.

Resources