I'm trying to get the following example working in a Xamarin.Mac project.
It's an AUGraph that connects a mixer to the default output. The mixer has one input which is a render callback that generates a sine wav.
var graph = new AUGraph();
var output = graph.AddNode(AudioComponentDescription.CreateOutput(AudioTypeOutput.Default));
var mixer = graph.AddNode(AudioComponentDescription.CreateMixer(AudioTypeMixer.MultiChannel));
if (graph.TryOpen() != 0)
{
throw new Exception();
}
var mixNode = graph.GetNodeInfo(mixer);
// configure mixer
if (mixNode.SetElementCount(AudioUnitScopeType.Input, 1) != AudioUnitStatus.OK)
{
throw new Exception();
}
if (mixNode.SetRenderCallback(HandleRenderDelegate, AudioUnitScopeType.Global, 0) != AudioUnitStatus.OK)
{
throw new Exception();
}
var outNode = graph.GetNodeInfo(output);
// define stream description
var desc = new AudioStreamBasicDescription();
desc.BitsPerChannel = 32;
desc.BytesPerFrame = 4;
desc.BytesPerPacket = 4;
desc.Format = AudioFormatType.LinearPCM;
desc.FormatFlags = AudioStreamBasicDescription.AudioFormatFlagsAudioUnitNativeFloat;
desc.FramesPerPacket = 1;
desc.ChannelsPerFrame = 2;
desc.SampleRate = 44100;
// set mixer input format
if (mixNode.SetFormat(desc, AudioUnitScopeType.Input, 0) != AudioUnitStatus.OK)
{
throw new Exception();
}
// connect mixer's output to the output
if (graph.ConnnectNodeInput(mixer, 0, output, 0) != AUGraphError.OK)
{
throw new Exception();
}
// set format of mixer's output
desc = mixNode.GetAudioFormat(AudioUnitScopeType.Output);
desc.SampleRate = 44100;
if (outNode.SetFormat(desc, AudioUnitScopeType.Input,0) != AudioUnitStatus.OK)
{
throw new Exception();
}
if (mixNode.SetFormat(desc, AudioUnitScopeType.Output) != AudioUnitStatus.OK)
{
throw new Exception();
}
if (graph.Initialize() != AUGraphError.OK)
{
throw new Exception();
}
if (graph.Start() != AUGraphError.OK)
{
throw new Exception();
}
The callback:
int sample = 0;
unsafe AudioUnitStatus HandleRenderDelegate(AudioUnitRenderActionFlags actionFlags, AudioTimeStamp timeStamp, uint busNumber, uint numberFrames, AudioBuffers data)
{
var left = (float*)data[0].Data;
var right = (float*)data[1].Data;
for (var i = 0; i < numberFrames; i++)
{
float sampleValue = (float)Math.Sin(sample * 2 * Math.PI * 440 / 44100);
left[i] = right[i] = sampleValue;
sample++;
}
return AudioUnitStatus.OK;
}
The callback is running and the buffer is being filled but no sound is generated. The example works in iOS with AudioTypeOutput.Remote being used in place of AudioTypeOutput.Default but for some reason macOS is not playing the sound. Any ideas?
The output volume of the mixer had to be set manually because it defaults to 0.
Related
I have a list-view which displays the current user medication schedule it currently sorts the list by the next due date and any medications that are past the current time are moved to the bottom of the list.
I was looking to make the medications that are past the current time to have a 'Tomorrow' button visible to it. Is this possible to do?
Currently this is how I am populating my listview:
/// <summary>
/// Gets User Medication list
/// </summary>
/// <returns>The user meds.</returns>
async public Task GetUserMedsOverdue()
{
MedicationListOverdue.ItemsSource = null;
UserMedTimesOverdue.Clear(); //Clears the list before calling API (prevents duplication)
main.Children.Add(MedicationListOverdue);
main.Children.Remove(NoMeds);
if (!CrossConnectivity.Current.IsConnected)
{
main.Children.Remove(MedicationListOverdue);
main.Children.Add(NoMeds);
NoMeds.Text = "No Internet Connection - Please check your connection";
NoMeds.Margin = new Thickness(35, 35, 20, 20);
BusyIndicator.IsRunning = false;
}
else
{
BusyIndicator.IsRunning = true;
//var usermed = await medicinemanager.CurrentClient.InvokeApiAsync<IEnumerable<usermedication>>("getusermednamejoin?userid=" + Helpers.Settings.UserKey + "", System.Net.Http.HttpMethod.Get, null);
try
{
var usermeddosagetimeoverdue = await medicinemanager.CurrentClient.InvokeApiAsync("getUserMedDosageTimeOverdue?userid=" + Helpers.Settings.UserKey, null, HttpMethod.Get, await App.LoadAPIKeyAsync(), null);
var responseContentoverdue = await usermeddosagetimeoverdue.Content.ReadAsStringAsync();
var useroverdue = JsonConvert.DeserializeObject<ObservableCollection<UserMedDosagePayLoadOverdue>>(responseContentoverdue);
//var usermeddosagetime = await medicinemanager.CurrentClient.InvokeApiAsync<IEnumerable<UserMedDosagePayLoad>>("getusermeddosagetime?userid=" + Helpers.Settings.UserKey + "", HttpMethod.Get, API, System.Threading.CancellationToken.None);
//null, System.Net.Http.HttpMethod.Get, API, System.Threading.CancellationToken.None);
Debug.WriteLine("UserMedDosageTime" + usermeddosagetimeoverdue);
foreach (UserMedDosagePayLoadOverdue item in useroverdue)
{
UserMedTimesOverdue.Add(item);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
FindNextDue(UserMedTimes);
//Get the List of meds the user is on
//UserMedList = await usermedicationmanager.getUserMedication();
//foreach (usermedication item in usermed)
//{
// if (item.IsActive != false)
// {
// UserMedList.Add(item);
// }
//}
if (UserMedTimes.Count != 0)
{
MedicationListOverdue.ItemsSource = UserMedTimesOverdue;
BusyIndicator.IsRunning = false;
}
else
{
Label MedLogo = new Label();
MedLogo.Text = peoplewithfonticon.meds;
MedLogo.FontFamily = "icomoon";
MedLogo.FontSize = 80;
MedLogo.Margin = new Thickness(30, 80, 0, 0);
Label MedTitle = new Label();
MedTitle.Text = "No \r\nMedications";
MedTitle.FontSize = 50;
MedTitle.FontAttributes = FontAttributes.Bold;
MedTitle.Margin = new Thickness(30, 0, 0, 0);
Label NoMeds = new Label();
NoMeds.Margin = new Thickness(30, 0, 0, 0);
main.Children.Remove(MedicationList);
//main.Children.Remove(btnHistory);
main.Children.Add(MedLogo);
main.Children.Add(MedTitle);
main.Children.Add(NoMeds);
NoMeds.Text = "You haven't added any medications to your medication cupboard yet";
//main.Children.Add(btnHistory);
BusyIndicator.IsRunning = false;
}
MedicationListOverdue.ItemsSource = UserMedTimesOverdue;
BusyIndicator.IsRunning = false;
}
}
//Order the collection of times so the next due is always first
TimeComparison = new List<TimeSpan>(TimeComparison.OrderBy(h => h.Hours).ThenBy(m => m.Minutes));
List<string> UserMedIDs = new List<string>();
for (int i = 0; i < TimeComparison.Count(); i++)
{
DateTime NextDue = DateTime.Now.Add(TimeComparison[i]);
DateTime NextDueToCompare = new DateTime(NextDue.Year, NextDue.Month, NextDue.Day, NextDue.Hour, NextDue.Minute, 0);
string NextDueComparisonString = NextDueToCompare.ToString("HH:mm:ss");
foreach (UserMedDosagePayLoad item in UserMedTimes)
{
if (item.Time == NextDueComparisonString && !UserMedIDs.Contains(item.Usermedid))
{
UserMedTimesFilteredList.Add(item);
UserMedIDs.Add(item.Usermedid);
}
}
UserMedTimes = medtimes;
MedicationList.ItemsSource = UserMedTimesFilteredList.OrderBy(X => NextDue);
BusyIndicator.IsRunning = false;
}
Pstcreation works properly with outlook installed.
Now, I am trying to create a pst file with standalone version of MAPI . But my process is stuck in oSession.LogOff(). Further if a comment that oSession.LogOff() line and subsequently call the CreatePstWithRedemption function to create an other pst, the process gets stuck in oSession.LogonPstStore
private bool CreatePstWithRedemption(EmailJTableArgs objJTablArgs, EmailFilterArgs objFilterArgs,
EmailExportRequestParams emailExportRequestParams)
{
RDOSession oSession = null;
IRDOStore store = null;
RDOFolder fFOlder = null;
RDOFolder childFolder = null;
IRDOItems folderItems = null;
var pstCreationStatus = false;
try
{
oSession = new RDOSession();
store = oSession.LogonPstStore(_fileName, 1, "PST");
var folderName = Path.GetFileNameWithoutExtension(_fileName);
if (store != null)
{
fFOlder = store.IPMRootFolder;
foreach (RDOFolder folder in fFOlder.Folders)
{
folder.Delete();
}
childFolder = fFOlder.Folders.Add(folderName, Type.Missing);
folderItems = childFolder.Items;
var resultOfGetEmails = new ResultGetEmails();
resultOfGetEmails.TotalCount = -1;
do
{
var journalEmails = GetEmailList(objFilterArgs, objJTablArgs, emailExportRequestParams,
resultOfGetEmails);
for (var i = 0; i < journalEmails.Count; i++)
{
IRDOMail mail = null;
try
{
mail = folderItems.Add(rdoItemType.olMailItem);
// populate mail fields
mail.Sent = true;
mail.Save();
}
finally
{
if (mail != null)
Marshal.ReleaseComObject(mail);
}
}
resultOfGetEmails.TotalCount -= BatchSize;
objJTablArgs.PageStartIndex += BatchSize;
} while (resultOfGetEmails.TotalCount > 0);
pstCreationStatus = true;
}
}
finally
{
// Do cleanup
if (oSession != null && oSession.LoggedOn)
{
try
{
oSession.Logoff();
Marshal.ReleaseComObject(oSession);
}
catch
{
}
}
}
return pstCreationStatus;
}
Note: The same thing works well when run in an environment where outlook is installed.
I'm try to convert a movie (.mp4) in audio (.mp3) with Xuggler. I use porcessing on OS X.
IMediaReader reader = ToolFactory.makeReader("/Users/nouv/Desktop/video1.mp4");
IMediaWriter writer = ToolFactory.makeWriter("/Users/nouv/Desktop/audioOutput.mp3", reader);
int sampleRate = 22050;
int channels = 1;
writer.addAudioStream(0, 0, ICodec.ID.CODEC_ID_MP3, channels, sampleRate);
reader.addListener(writer);
try {
while (reader.readPacket() == null)
;
} finally {}
I have this error : IllegalArgumentException : stream[0] is not video
Exception in thread "Animation Thread" java.lang.IllegalArgumentException: stream[0] is not video
at com.xuggle.mediatool.MediaWriter.encodeVideo(MediaWriter.java:754)
at com.xuggle.mediatool.MediaWriter.encodeVideo(MediaWriter.java:783)
at com.xuggle.mediatool.MediaWriter.onVideoPicture(MediaWriter.java:1434)
at com.xuggle.mediatool.AMediaToolMixin.onVideoPicture(AMediaToolMixin.java:166)
at com.xuggle.mediatool.MediaReader.dispatchVideoPicture(MediaReader.java:610)
at com.xuggle.mediatool.MediaReader.decodeVideo(MediaReader.java:519)
at com.xuggle.mediatool.MediaReader.readPacket(MediaReader.java:475)
at xuggle.setup(xuggle.java:135)
at processing.core.PApplet.handleDraw(PApplet.java:2117)
at processing.core.PGraphicsJava2D.requestDraw(PGraphicsJava2D.java:193)
at processing.core.PApplet.run(PApplet.java:2020)
at java.lang.Thread.run(Thread.java:680)
I tried with .mp4 , .mov and .flv movie and I have the same error.
IContainer container = IContainer.make();
int result = container.open(inputFilename, IContainer.Type.READ, null);
// check if the operation was successful
if (result<0)
throw new RuntimeException("Failed to open media file");
int numStreams = container.getNumStreams();
int audioStreamId = -1;
IContainer writer = IContainer.make();
writer.open(outputFilename, IContainer.Type.WRITE, IContainerFormat.make());
for (int i=0; i<numStreams; i++) {
IStream stream = container.getStream(i);
IStreamCoder coder = stream.getStreamCoder();
IStreamCoder audioCoder = IStreamCoder.make(IStreamCoder.Direction.ENCODING, coder);
if( coder.getCodecType() == ICodec.Type.CODEC_TYPE_AUDIO){
coder.open(IMetaData.make(), IMetaData.make());
audioStreamId = i;
ICodec inputCodec = ICodec.findDecodingCodec(ICodec.ID.CODEC_ID_MP3);
if (inputCodec == null)
throw new IllegalArgumentException("could not find input codec id");
if (audioStreamId == -1)
throw new RuntimeException("could not find audio stream in container: "+inputFilename);
writer.addNewStream(audioCoder);
if(writer.writeHeader() == 0)
{
IPacket packet = IPacket.make();
while(container.readNextPacket(packet) >= 0){
if(packet.getStreamIndex() == audioStreamId)
{
if(coder.isOpen()){
writer.writePacket(packet);
} else {throw new RuntimeException("Could not open Coder"); }
}
}
}else {throw new RuntimeException("Header not Written for writer container.");}
}
coder.close(); audioCoder.close();
}
writer.writeTrailer();
writer.close();
hope this helps... :)
My J2ME midlet could retrieves message in Chinese character from a PHP server but it's garbled. The server basically returns the response string and by detecting the first 2 characters. AA = good, anything else indicates error of which the message is to be passed to the calling function for display
InputStream is = null;
StringBuffer sb = null;
String str = "";
HttpConnection http = null;
DataOutputStream dos = null;
try
{
URL = login.getURL();
URL += ctlFunction + "/" + uriStr;
URL = EncodeURL(URL);
//System.out.println(URL);
if(!ctlFunction.equals("login"))
{
msg += "&user=" + login.getUsername();
msg += "&token=" + login.getToken();
}
msg += "&lang=" + System.getProperty("microedition.locale");
// establish the connection
http = (HttpConnection) Connector.open(URL);
http.setRequestMethod(HttpConnection.POST);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setRequestProperty("Content-length", ""+EncodeURL(msg).getBytes().length);
dos = http.openDataOutputStream();
byte[] request_body = EncodeURL(msg).getBytes();
for (int i = 0; i < request_body.length; i++)
{
dos.writeByte(request_body[i]);
}
// server response
if (http.getResponseCode() == HttpConnection.HTTP_OK)
{
is = http.openDataInputStream();
int length = (int) http.getLength();
if (length != -1)
{
// Read data in one chunk
byte serverData[] = new byte[length];
is.read(serverData);
str = new String(serverData);
}
else // Length not available...
{
ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
int ch;
while ((ch = is.read()) != -1)
bStrm.write(ch);
str = new String(bStrm.toByteArray());
bStrm.close();
}
}
else
{
networkError();
}
}
catch (Exception e)
{
System.err.println("Error3: " + e.toString());
networkError(e.toString());
}
finally
{
if (is != null)
is.close();
if (!str.equals(""))
post = str;
else
networkError();
if (http != null)
http.close();
}
if (post != null)
{
String fate = post.substring(0, 2);
if(fate.equals("AA"))
{
if(ctlFunction.equals("login"))
{
String rawPost = post.substring(2);
Vector v = new Vector();
int index = 0;
//find the first occurrence of the SPLITTER
int endIndex = rawPost.indexOf(SPLITTER, index);
String item = "";
//extract the items until the end of the last SPLITTER found in the rawPost string
while(endIndex != -1)
{
item = rawPost.substring(index, endIndex);
index = endIndex + 1;
endIndex = rawPost.indexOf(SPLITTER, index);
v.addElement(item);
}
//extract the rest of the rawPost (the text item)
item = rawPost.substring(index);
v.addElement(item);
String[] ret = new String[v.size()];
v.copyInto(ret);
login.setToken(ret[0]);
login.setToday(ret[1]);
login.setNextDrawDay(ret[2]);
}
midlet.returnResults(post.substring(2), getCurrentDisplay(), ctlFunction);
}
else
{
String errmessage = post.substring(2);
System.out.println(post);
midlet.showInfo(post, getCurrentDisplay());
}
}
else
{
networkError();
}
On the PHP server, I have set the header to UTF-8 encoding
<?php header("Content-Type:text/plain; charset=utf-8"); ?>
What could possibly be wrong?
I found that this user has the same problem and it's been answered
Reading UTF8 strings from a server through http using MIDP. Kudos to the answer.
I basically edited my MIDP code from
// is = http.openDataInputStream();
// int length = (int) http.getLength();
// if (length != -1)
// {
// // Read data in one chunk
// byte serverData[] = new byte[length];
// is.read(serverData);
// str = new String(serverData);
// }
// else // Length not available...
// {
// ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
// int ch;
// while ((ch = is.read()) != -1)
// bStrm.write(ch);
//
// str = new String(bStrm.toByteArray());
// bStrm.close();
// }
to
Reader r = new InputStreamReader(http.openInputStream(), "UTF-8");
int ch;
while((ch = r.read()) != -1)
str = str + (char)ch;
just wondering though why does reading bytes messes up the UTF-8 characters?
The below code which uses npoi to create excel documents displays images in open office calc but not in excel.
If i open the doc in calc and save the document and then open the document in excel i can then see the images in excel.
Here is the code.
public static byte[] CreateExcel(CampaignViewModel viewModel, string fileName)
{
byte[] output;
using (FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(#"\Data\templates\NPOITemplate.xls"), FileMode.Open, FileAccess.ReadWrite))
{
var templateWorkbook = new HSSFWorkbook(fs, true);
var sheet = templateWorkbook.GetSheet("Sheet1");
var patriarch = sheet.CreateDrawingPatriarch();
var leftFieldHeaders = CsvHelper.GetMatrixAllLeftFields();
var productHeaders = CsvHelper.GetMatrixProducts(viewModel.ProductCampaigns);
var totalCols = leftFieldHeaders.Count + productHeaders.Count;
var colWidth = 5000;
for (int i = 0; i < totalCols; i++)
{
sheet.SetColumnWidth(i, colWidth);
}
var imageRow = sheet.CreateRow(0);
imageRow.Height = 2000;
var imageCellCount = 0;
foreach (var header in leftFieldHeaders)
{
imageRow.CreateCell(imageCellCount).SetCellValue("");
imageCellCount++;
}
foreach (var product in viewModel.ProductCampaigns)
{
try
{
var anchor = new HSSFClientAnchor(0, 0, 0, 0, imageCellCount, 0, imageCellCount, 0);
anchor.AnchorType = 2;
var path = HttpContext.Current.Server.MapPath(product.Product.ImageThumbUrl);
var picture = patriarch.CreatePicture(anchor, LoadImage(#path, templateWorkbook));
picture.Resize();
picture.LineStyle = HSSFPicture.LINESTYLE_SOLID;
}
catch (Exception)
{
}
imageCellCount++;
}
using (MemoryStream ms = new MemoryStream())
{
templateWorkbook.Write(ms);
output = ms.ToArray();
}
}
return output;
}
public static int LoadImage(string path, HSSFWorkbook wb)
{
try
{
var file = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
var buffer = new byte[file.Length];
file.Read(buffer, 0, (int)file.Length);
return wb.AddPicture(buffer, PictureType.JPEG);
}
catch (Exception)
{
return 0;
}
}
i've resolved the above in a round about way. Turns out i didn't really need to use the template and could just create the xls from scratch. This add's a bit more meta data to the file which i suspect was the issue
public static byte[] CreateExcel2(CampaignViewModel viewModel, ICollection<DeliveryPoint> deliveryPoints, string fileName)
{
FileContentResult fileContentResult;
byte[] output;
var matrixCampaignLines = viewModel.MatrixCampaignLines;
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "NPOI Team";
hssfworkbook.DocumentSummaryInformation = dsi;
////create a entry of SummaryInformation
SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Subject = "NPOI SDK Example";
hssfworkbook.SummaryInformation = si;
var sheet = hssfworkbook.CreateSheet("Sheet1");
var patriarch = sheet.CreateDrawingPatriarch();
var leftFieldHeaders = (viewModel.Campaign.EnableNameOnCampaign) ? CsvHelper.GetMatrixAllLeftFields() : CsvHelper.GetMatrixAllLeftFieldsWithoutName();
var productHeaders = CsvHelper.GetMatrixProducts(viewModel.ProductCampaigns);
var totalCols = leftFieldHeaders.Count + productHeaders.Count;
var colWidth = 5000;
for (int i = 0; i < totalCols; i++)
{
sheet.SetColumnWidth(i, colWidth);
}
var imageRow = sheet.CreateRow(0);
imageRow.Height = 2000;
var imageCellCount = 0;
foreach (var header in leftFieldHeaders)
{
imageRow.CreateCell(imageCellCount).SetCellValue("");
imageCellCount++;
}
foreach (var product in viewModel.ProductCampaigns)
{
try
{
var anchor = new HSSFClientAnchor(0, 0, 0, 0, imageCellCount, 0, imageCellCount, 0);
anchor.AnchorType = 2;
var path = HttpContext.Current.Server.MapPath(product.Product.ImageThumbUrl);
var picture = patriarch.CreatePicture(anchor, LoadImage(#path, hssfworkbook));
picture.Resize();//Comment this line if your code crashes.
picture.LineStyle = HSSFPicture.LINESTYLE_SOLID; might not
}
catch (Exception)
{
}
imageCellCount++;
}
using (MemoryStream ms = new MemoryStream())
{
hssfworkbook.Write(ms);
output = ms.ToArray();
}
return output;
}
public static int LoadImage(string path, HSSFWorkbook wb)
{
try
{
var file = new FileStream(path, FileMode.Open, FileAccess.Read);
var buffer = new byte[file.Length];
file.Read(buffer, 0, (int)file.Length);
return wb.AddPicture(buffer, PictureType.JPEG);
}
catch (Exception)
{
return 0;
}
}
I got it right now.
I am using
try
{
ISheet sheet = templateWorkbook.GetSheet(sheetName);
HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();
//create the anchor
HSSFClientAnchor anchor;
anchor = new HSSFClientAnchor(0, 0, 255, 255,
start.Col, start.Row, end.Col, end.Row);
anchor.AnchorType = 2;
patriarch.CreatePicture(anchor,
LoadImage(imagePath, templateWorkbook));
}
catch (IOException ioe)
{
}
and LoadImage() method which returns path from the server.
Use this one. It runs fine.