CrossTextToSpeech.Current.Speak with delay - xamarin

i try to create Android App for my kinder to read list from String with pause between every string
i use Xamarin with xamarin.texttospeech.plugin with C#
List<String> listword = new List<string>();
private void AddBT_Clicked(object sender, EventArgs e)
{
listword.Add(MainEntry.Text);
MainEntry.Text = "";
}
private void TestBT_Clicked(object sender, EventArgs e)
{
for (int i = 0; i < listword.Count; i++)
{
CrossTextToSpeech.Current.Speak(text: listword[i], crossLocale: null, pitch: (float)1, speakRate: (float)0.5, volume: 1);
thread.sleep(30000);
}
}
the Problem is the App wait until the last word in the list and then speak all of them
what i have to do .

Related

Camera timer animation on UWP

I am developing an UWP application, and one of my page is actually for user to take photo of them. In the page, I have timers for user to select before they take picture.
However, I wish to have a timer shown, counting down in the camera screen, so that the user know how much time is left for them to prepare, before the picture is taken.
Any idea on how I can do that? Thank you!
Just in case it is needed, here is my codes for the timers and the take picture buttons:
private async void PhotoButton_Click(object sender, RoutedEventArgs e)
{
//If preview is not running, no preview frames can be acquired
if (!_isPreviewing) return;
await Task.Delay(TimeSpan.FromSeconds(_seconds));
await TakePhotoAsync();
await GetPreviewFrameAsSoftwareBitmapAsync();
PreviewFrameBackground.Visibility = Visibility.Visible;
}
private void Timer_3sec_Click(object sender, RoutedEventArgs e)
{
Timer_5sec.Opacity = 0.2;
Timer_7sec.Opacity = 0.2;
Timer_3sec.Opacity = 1.0;
_seconds = 3;
}
private void Timer_5sec_Click(object sender, RoutedEventArgs e)
{
Timer_3sec.Opacity = 0.2;
Timer_7sec.Opacity = 0.2;
Timer_5sec.Opacity = 1.0;
_seconds = 5;
}
private void Timer_7sec_Click(object sender, RoutedEventArgs e)
{
Timer_3sec.Opacity = 0.2;
Timer_5sec.Opacity = 0.2;
Timer_7sec.Opacity = 1.0;
_seconds = 7;
}
You can use a DispatcherTimer to solve your problem.
Here a little code sample how you can do that (The sample dont show how to take the capture or to show the remaining seconds, just to calculate them!)
Class-Parameters:
private int _startTime;
private DispatcherTimer _timer = new DispatcherTimer();
Methods:
private void StartTimer()
{
_timer.Interval = TimeSpan.FromMilliseconds(500);
_timer.Tick += Timer_Tick;
_startTime = Environment.TickCount;
_timer.Start();
}
private void Timer_Tick(object sender, object e)
{
var remainingSeconds = _seconds - TimeSpan.FromMilliseconds(Environment.TickCount - _startTime).Seconds;
if(remainingSeconds <= 0)
{
_timer.Stop();
_timer.Tick -= Timer_Tick;
timerText.Text = "0 Seconds";
//Capture Image
} else
{
timerText.Text = "" + remainingSeconds + " Seconds";
}
}
You need to call the StartTimer-Method in you Click-Methods, after setting the _seconds.

Issue while Playing, the recorded audio in WP7

Hi Developers,
If we save the recorded voice as a mp3 file. we get the error while opening the file as Windows Media Player cannot play the file. The Player might not support the file type or might not support the codec that was used to compress the file.
Please Give a Solution to overcome this Issue ....
Here is My Source code
namespace Windows_Phone_Audio_Recorder
{
public partial class MainPage : PhoneApplicationPage
{
MemoryStream m_msAudio = new MemoryStream();
Microphone m_micDevice = Microphone.Default;
byte[] m_baBuffer;
SoundEffect m_sePlayBack;
ViewModel vm = new ViewModel();
long m_lDuration = 0;
bool m_bStart = false;
bool m_bPlay = false;
private DispatcherTimer m_dispatcherTimer;
public MainPage()
{
InitializeComponent();
SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;
DataContext = vm;
m_dispatcherTimer = new DispatcherTimer();
m_dispatcherTimer.Interval = TimeSpan.FromTicks(10000);
m_dispatcherTimer.Tick += frameworkDispatcherTimer_Tick;
m_dispatcherTimer.Start();
FrameworkDispatcher.Update();
//icBar.ItemsSource = vm.AudioData;
}
void frameworkDispatcherTimer_Tick(object sender, EventArgs e)
{
FrameworkDispatcher.Update();
}
private void btnStart_Click(object sender, RoutedEventArgs e)
{
m_bStart = true;
tbData.Text = "00:00:00";
m_lDuration = 0;
m_micDevice.BufferDuration = TimeSpan.FromMilliseconds(1000);
m_baBuffer = new byte[m_micDevice.GetSampleSizeInBytes(m_micDevice.BufferDuration)];
//m_micDevice.BufferReady += new EventHandler(m_Microphone_BufferReady);
m_micDevice.BufferReady += new EventHandler<EventArgs>(m_Microphone_BufferReady);
m_micDevice.Start();
}
void m_Microphone_BufferReady(object sender, EventArgs e)
{
m_micDevice.GetData(m_baBuffer);
Dispatcher.BeginInvoke(()=>
{
vm.LoadAudioData(m_baBuffer);
m_lDuration++;
TimeSpan tsTemp = new TimeSpan(m_lDuration * 10000000);
tbData.Text = tsTemp.Hours.ToString().PadLeft(2, '0') + ":" + tsTemp.Minutes.ToString().PadLeft(2, '0') + ":" + tsTemp.Seconds.ToString().PadLeft(2, '0');
}
);
//this.Dispatcher.BeginInvoke(new Action(() => vm.LoadAudioData(m_baBuffer)));
//this.Dispatcher.BeginInvoke(new Action(() => tbData.Text = m_baBuffer[0].ToString() + m_baBuffer[1].ToString() + m_baBuffer[2].ToString() + m_baBuffer[3].ToString()));
m_msAudio.Write(m_baBuffer,0, m_baBuffer.Length);
}
private void btnStop_Click(object sender, RoutedEventArgs e)
{
if (m_bStart)
{
m_bStart = false;
m_micDevice.Stop();
ProgressPopup.IsOpen = true;
}
if (m_bPlay)
{
m_bPlay = false;
m_sePlayBack.Dispose();
}
}
private void btnPlay_Click(object sender, RoutedEventArgs e)
{
m_bPlay = true;
m_sePlayBack = new SoundEffect(m_msAudio.ToArray(), m_micDevice.SampleRate, AudioChannels.Mono);
m_sePlayBack.Play();
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
if (txtAudio.Text != "")
{
IsolatedStorageFile isfData = IsolatedStorageFile.GetUserStoreForApplication();
string strSource = txtAudio.Text + ".wav";
int nIndex = 0;
while (isfData.FileExists(txtAudio.Text))
{
strSource = txtAudio.Text + nIndex.ToString().PadLeft(2, '0') + ".wav";
}
IsolatedStorageFileStream isfStream = new IsolatedStorageFileStream(strSource, FileMode.Create, IsolatedStorageFile.GetUserStoreForApplication());
isfStream.Write(m_msAudio.ToArray(), 0, m_msAudio.ToArray().Length);
isfStream.Close();
}
this.Dispatcher.BeginInvoke(new Action(() => ProgressPopup.IsOpen = false));
}
}
}
DotNet Weblineindia
my Source Code For UPLOADING A AUDIO TO PHP SERVER:
public void UploadAudio()
{
try
{
if (m_msAudio != null)
{
var fileUploadUrl = "uploadurl";
var client = new HttpClient();
m_msAudio.Position = 0;
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StreamContent(m_msAudio), "uploaded_file", strFileName);
// upload the file sending the form info and ensure a result.it will throw an exception if the service doesn't return a valid successful status code
client.PostAsync(fileUploadUrl, content)
.ContinueWith((postTask) =>
{
try
{
postTask.Result.EnsureSuccessStatusCode();
var respo = postTask.Result.Content.ReadAsStringAsync();
string[] splitChar = respo.Result.Split('"');
FilePath = splitChar[3].ToString();
Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/VoiceSlider.xaml?FName=" + strFileName, UriKind.Relative)));
}
catch (Exception ex)
{
// Logger.Log.WriteToLogger(ex.Message);
MessageBox.Show("voice not uploaded" + ex.Message);
}
});
}
}
catch (Exception ex)
{
//Logger.Log.WriteToLogger(ex.Message + "Error occured while uploading image to server");
}
}
First of all Windows Phone does not allow to record .mp3 files. So, the .mp3 file that you are saving will not be played by Windows Phone player.
Have a look at this. This demo is working fine for recording .wav file.
If you wish to save other formats like .aac,.amr then user AudioVideoCaptureDevice class.

How can I use Bing Maps to get my current location?

My code is not working, it's show the whole world map. I just want to get current location and place a pushpin at it. I have been through Google and none of the examples works.
This is my code.
GeoCoordinateWatcher watcher;
// Constructor
public MainPage()
{
InitializeComponent();
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
if (watcher == null)
{
Console.WriteLine(watcher);
watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
watcher.MovementThreshold = 20;
watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
}
watcher.Start();
}
private void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
Pushpin pin = new Pushpin();
pin.Template = this.Resources["currentPushPin"] as ControlTemplate;
pin.Location = watcher.Position.Location;
mapControl.Items.Add(pin);
myMap.SetView(watcher.Position.Location, 15.0);
watcher.Stop();
}
void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
if (e.Position.Location.IsUnknown)
{
MessageBox.Show("Please wait while your prosition is determined....");
return;
}
Pushpin pin = new Pushpin();
myMap.Center = new GeoCoordinate(e.Position.Location.Latitude, e.Position.Location.Longitude);
pin.Template = this.Resources["currentPushPin"] as ControlTemplate;
pin.Location = new GeoCoordinate(e.Position.Location.Latitude, e.Position.Location.Longitude);
myMap.SetView(watcher.Position.Location, 18.0);
}
You start the GeoCordinateWatcher in PhoneApplicationPage_Loaded but this method never gets called. Add
Loaded+=PhoneApplicationPage_Loaded
at the end of the constructor.

Unable to show the selected item in the Wp7 Listpicker control

Basically i am trying to pull the contacts from the phone and showing them in the Listpicker control for a feature in my app. I have two Listpickers, one for name of contacts list and the other showing the list of phonenumbers for the chosen contact.
Here is my code:
//Declarations
ContactsSearchEventArgs e1;
String SelectedName;
String SelectedNumber;
List<string> contacts = new List<string>();
List<string> phnum = new List<string>();
public AddressBook() // Constructor
{
InitializeComponent();
Contacts contacts = new Contacts();
contacts.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(contacts_SearchCompleted);
contacts.SearchAsync(string.Empty,FilterKind.None,null);
}
void contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
{
e1 = e;
foreach (var result in e.Results)
{
if (result.PhoneNumbers.Count() != 0)
{
contacts.Add(result.DisplayName.ToString());
}
}
Namelist.ItemsSource = contacts;
}
private void Namelist_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SelectedName = (sender as ListPicker).SelectedItem.ToString();
phnum.Clear();
foreach (var result in e1.Results)
{
if (SelectedName == result.DisplayName)
{
phnum.Add(result.PhoneNumbers.FirstOrDefault().ToString());
}
}
Numbers.ItemsSource = phnum;
}
private void Numbers_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SelectedNumber = (sender as ListPicker).SelectedItem.ToString();
}
Am able to populate the Numberlist with phonenumbers for the chosen name at the Listpicker background, but the number is not showing up in the front. I think Numbers_SelectionChanged() event is called only one time when the page loads and am not seeing it triggerd when i change the contact list. Anyone has an idea of where am going wrong ?
If you change
List<string>
To
ObservableCollection<string>
this should work.
Also then you only need to set the ItemSource once, in Xaml or you constructor.
But you may run into another issue with the November 2011 Toolkit and ListPicker.
See more in thread.
private void Namelist_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SelectedName = (sender as ListPicker).SelectedItem.ToString();
phnum = new List<string>(); // Changed instead of phnum.Clear()
foreach (var result in e1.Results)
{
if (SelectedName == result.DisplayName)
{
phnum.Add(result.PhoneNumbers.FirstOrDefault().ToString());
}
}
Numbers.ItemsSource = phnum;
}
This works !!. While debugging i found its phnum.Clear() giving a problem. So i thought to create a new instance of phnum list for selected contact.

I am trying to run Mars Image Viewer Sample from OCT 2010 MSDN Magazine but running into some errors?

Here is the code-
private void getImageIDs()
{
Uri serviceUri = new Uri("https://api.sqlazureservices.com/NasaService.svc/MER/Images?missionId=1&$format=raw");
WebClient recDownloader = new WebClient();
recDownloader.Headers["$accountKey"] = "<enter your key>";
recDownloader.Headers["$uniqueUserID"] = "<enter your id>";
recDownloader.OpenReadCompleted += new OpenReadCompletedEventHandler(recDownloader_OpenReadCompleted);
recDownloader.OpenReadAsync(serviceUri);
}
private void recDownloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
Stream responseStream = e.Result;
XNamespace ns = "http://www.w3.org/2005/Atom";
XElement marsStuff = XElement.Load(responseStream);
entries = marsStuff.Elements(ns + "entry");
string imageID = (string)entries.ElementAt<XElement>(index).Element(ns + "title").Value;
Console.WriteLine(imageID);
getImage(imageID);
}
}
private void getImage(string ID)
{
Uri serviceUri = new Uri("https://api.sqlazureservices.com/NasaService.svc/MER/Images/" + ID + "?$format=raw");
WebClient imgDownloader = new WebClient();
imgDownloader.Headers["$accountKey"] = "<enter your key>";
imgDownloader.Headers["$uniqueUserID"] = "<enter your id>";
imgDownloader.OpenReadCompleted += new OpenReadCompletedEventHandler(imgDownloader_OpenReadCompleted);
imgDownloader.OpenReadAsync(serviceUri);
}
private void imgDownloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
Stream imageStream = e.Result;
BitmapImage imgsrc = new BitmapImage();
imgsrc.SetSource(imageStream);
MarsImage.Source = imgsrc;
}
}
private void appbar_BackButton_Click(object sender, EventArgs e)
{
if (index > 0)
{
index--;
XNamespace ns = "http://www.w3.org/2005/Atom";
string imageID = (string)entries.ElementAt<XElement>(index).Element(ns + "Title").Value;
getImage(imageID);
}
}
private void appbar_ForwardButton_Click(object sender, EventArgs e)
{
if ( (index + 1) < entries.Count<XElement>())
{
index++;
XNamespace ns = "http://www.w3.org/2005/Atom";
string imageID = (string)entries.ElementAt<XElement>(index).Element(ns + "Title").Value;
getImage(imageID);
}
}
}
I am not seeing any images. Anybody able to get this sample running?
This one? http://msdn.microsoft.com/en-us/magazine/gg232764.aspx
If so, there are some things that had to change to make it work, as the original code was on a preview version of the WP7 tools, as listed in the comments there:
Delete (or comment out) the following lines of code from MainPage.xaml.cs
recDownloader.Headers["$accountKey"] = "<Your account key>";
recDownloader.Headers["$uniqueUserID"] = "<Your user ID>";
imgDownloader.Headers["$accountKey"] = "<Your account key>";
imgDownloader.Headers["$uniqueUserID"] = "<Your user ID>";
Replace the two recDownloader lines of code with:
recDownloader.Credentials = new NetworkCredential("accountKey", "<Your account key>");
Replace the two imgDownloader lines of code with:
imgDownloader.Credentials = new NetworkCredential("accountKey", "<Your account key>");

Resources