How can I play an audio random when a button is clicked in WP8? - windows-phone-8

I have tried this code, but it doesn't work.
public void Play()
{
int randomIndex = -1;
var sound1 = "/Assets/Audio/baby-crying-08.mp3";
var sound2 = "/Assets/Audio/sound1.wav";
string [] rawRef = {sound1,sound2};
MediaElement mp = new MediaElement();
try
{
randomIndex = random.Next(rawRef.Length);
mp.Source = new Uri(rawRef[randomIndex], UriKind.RelativeOrAbsolute);
mp.Play();
}
catch (Exception e)
{
}
}
how to play an audio file randomly ?

I had this problem. You need use Play() method after media opened. Moreover you need add MediaElement control to your xaml. Remember to check your files paths. Look for this code:
MainPage.xaml.cs:
private Random _random = new Random();
public void Play()
{
int randomIndex = -1;
var sound1 = "/Assets/cos.wav";
var sound2 = "/Assets/xx.mp3";
string[] rawRef = { sound1, sound2 };
try
{
randomIndex = _random.Next(rawRef.Length);
MediaElement.Source = new Uri(rawRef[randomIndex], UriKind.RelativeOrAbsolute);
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
}
private void OnMediaOpened(object sender, RoutedEventArgs e)
{
MediaElement.Play();
}
private void OnMediaFailed(object sender, ExceptionRoutedEventArgs e)
{
Debug.WriteLine("Exception: {0}, Sound: {1}", e.ErrorException.Message, MediaElement.Source.ToString());
}
MainPage.xaml:
<MediaElement x:Name="MediaElement" AutoPlay="False"
MediaOpened="OnMediaOpened"
MediaFailed="OnMediaFailed" />

Try this
MainPage.xaml:
<MediaElement x:Name="audio0" Source="/Audio/xh.mp3" AutoPlay="False" />
<MediaElement x:Name="audio1" Source="/Audio/y.mp3" AutoPlay="False" />
MainPage.xaml.cs:
private Random _random = new Random();
private int randomIndex = -1;
public void Playsound()
{
MediaElement [] rawRef = { audio0, audio1 };
try
{
randomIndex = _random.Next(rawRef.Length);
if(randomIndex==0)
{
audio0.Play();
}
else if (randomIndex == 1)
{
audio1.Play();
}
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
MessageBox.Show("Message:"+e.Message);
}
}

Related

Accurate Windows phone 8.1 geolocation?

Im working with windows phone 8.1 geolocation. The problem that I currently have is that my code only shows the first numbers of my coordinate. Example: If the coordinate is "41.233" the app only shows "41.00" . I need it to be as accurate as possible. In case it matters, im using windows phone 8.1 emulator to try the app, not an actual phone.
My code:
public sealed partial class MainPage : Page
{
bool shouldSend = false;
DispatcherTimer timer = new DispatcherTimer();
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
private async Task GetLocation()
{
Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracy = Windows.Devices.Geolocation.PositionAccuracy.High;
try
{
Geoposition geoposition = await geolocator.GetGeopositionAsync(
maximumAge: TimeSpan.FromSeconds(1),
timeout: TimeSpan.FromSeconds(10)
);
LatitudeTxt.Text = geoposition.Coordinate.Latitude.ToString("0.00");
LongitudeTxt.Text = geoposition.Coordinate.Longitude.ToString("0.00");
LatLonTxt.Text = LatitudeTxt.Text + ", " + LongitudeTxt.Text;
var speed = geoposition.Coordinate.Speed.ToString();
ProcessingTxt.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
string result = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
"http://proyecto-busways.rhcloud.com/colectivos?p=lta123&l=80&d=moyano&lat=" + LatitudeTxt.Text + "&lon=" + LongitudeTxt.Text + "&v=" + speed + "&Accion=Agregar");
request.ContinueTimeout = 4000;
request.Credentials = CredentialCache.DefaultNetworkCredentials;
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
{
if (response.StatusCode == HttpStatusCode.OK)
{
//To obtain response body
using (Stream streamResponse = response.GetResponseStream())
{
using (StreamReader streamRead = new StreamReader(streamResponse, Encoding.UTF8))
{
result = streamRead.ReadToEnd();
}
}
}
}
}
catch (Exception ex)
{
ProcessingTxt.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
if ((uint)ex.HResult == 0x80004004)
{
// the application does not have the right capability or the location master switch is off
}
//else
{
// something else happened acquring the location
}
}
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// TODO: Prepare page for display here.
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
}
private async void StartSending_Click(object sender, RoutedEventArgs e)
{
await GetLocation();
timer.Tick += timer_Tick;
timer.Interval = new TimeSpan(0, 0, 5);
timer.Start();
StartSending.IsEnabled = false;
}
async void timer_Tick(object sender, object e)
{
ProcessingTxt.Visibility = Windows.UI.Xaml.Visibility.Visible;
await GetLocation();
}
private void EndSending_Click(object sender, RoutedEventArgs e)
{
timer.Tick -= timer_Tick;
timer.Stop();
StartSending.IsEnabled = true;
EndSending.IsEnabled = false;
}
private void GPS_Tapped(object sender, TappedRoutedEventArgs e)
{
Frame.Navigate(typeof(ContactPage));
}
}
Thanks for your help!
Did you try out the Geolocator.DesiredAccuracyInMeters property?
geolocator.DesiredAccuracyInMeters = 3;
Reference & Sample
In this point LatitudeTxt.Text = geoposition.Coordinate.Latitude.ToString("0.00");
LongitudeTxt.Text = geoposition.Coordinate.Longitude.ToString("0.00");
You indicated that you have 0.00 decimals, for more accuracy you should put 0.000000

Recording sound in temporary file on windows phone 8

This is my code for recording sound in temporary file. when i record sound and then listen to playback, everything goes well, but when i click again on playback button, i get this error:
How can i solve this problem?
Code:
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows;
using System.Windows.Controls;
using Coding4Fun.Toolkit.Audio;
using Coding4Fun.Toolkit.Audio.Helpers;
namespace AudioRecorder.UserControls
{
public partial class SoundRecorderPanel : UserControl
{
private MicrophoneRecorder _recorder = new MicrophoneRecorder();
private List<IsolatedStorageFileStream> _audioList = new List<IsolatedStorageFileStream>();
private int _counter;
public SoundRecorderPanel()
{
InitializeComponent();
}
private void ButtonRecord_OnChecked(object sender, RoutedEventArgs e)
{
_recorder.Start();
}
private void ButtonRecord_OnUnchecked(object sender, RoutedEventArgs e)
{
_recorder.Stop();
SaveTempAudio(_recorder.Buffer);
}
private void SaveTempAudio(MemoryStream buffer)
{
if (_counter==2)
return;
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
var bytes = buffer.GetWavAsByteArray(_recorder.SampleRate);
var tempFileName = "tempwaveFile_"+_counter;
IsolatedStorageFileStream audioStream = isoStore.CreateFile(tempFileName);
audioStream.Write(bytes,0,bytes.Length);
_audioList.Add(audioStream);
_counter++;
}
}
private void ButtonPlayBack_OnClick(object sender, RoutedEventArgs e)
{
var index = int.Parse(((Button) sender).Tag.ToString());
var audioPlayer = new MediaElement {AutoPlay = true};
if (index < _audioList.Count)
{
audioPlayer.SetSource(_audioList[index]);
LayoutRoot.Children.Add(audioPlayer);
audioPlayer.Play();
}
}
}
}
You can 100% use a using block. Issue was how you were attempting to access the stream in the separate event. Reopen it rather than attempt to save a reference in an index to the stream.
using (var stream = new IsolatedStorageFileStream(_fileName, FileMode.Open, storageFolder))
{
playBack.SetSource(stream);
playBack.Play();
}
Use the sample code:
https://coding4fun.codeplex.com/SourceControl/latest#source/Coding4Fun.Toolkit.Test.WindowsPhone.Common/Samples/Audio.xaml.cs
I solved my problem , it's weird but it seems using(){} does not work ! and i disposed IsolatedStorageFile and IsolatedStorageFileStream manually . and also i changed the code under ButtonPlayBack click event . this is my new code for someone who has a same problem .
private void SaveTempAudio(MemoryStream buffer)
{
if (_counter == 2)
return;
var isoStore = IsolatedStorageFile.GetUserStoreForApplication();
var bytes = buffer.GetWavAsByteArray(_recorder.SampleRate);
var tempFileName = "tempwave_" + _counter;
var audioStream = isoStore.CreateFile(tempFileName);
audioStream.Write(bytes, 0, bytes.Length);
_audioList.Add(audioStream);
_counter++;
isoStore.Dispose();
audioStream.Close();
audioStream.Dispose();
}
private void ButtonPlayBack_OnClick(object sender, RoutedEventArgs e)
{
var index = int.Parse(((Button) sender).Tag.ToString());
var fileName = "tempwave_" + ((Button) sender).Tag;
if (index >= _audioList.Count)
return;
var isoStorage = IsolatedStorageFile.GetUserStoreForApplication();
var fileStream = isoStorage.OpenFile(fileName, FileMode.Open, FileAccess.Read);
SoundPlayer.SetSource(fileStream);
SoundPlayer.Play();
isoStorage.Dispose();
fileStream.Close();
fileStream.Dispose();
}

Windows Phone 8 Page Navigation

I have a problem that I can't really figure out, and I am really desperate now - I've no idea why it's happening:(
So here is the problem: I am writing a kind of Guess that Tune app. The first page is a menu page, that a user can press "Play" button, and he will navigate to a GenreSelectPage where he selects a genre and navigates to a GamePage. I wanted to handle BackButtonPress on GamePage - when a user hits BackButton, he navigates to MainPage, not GenreSelectPage. Here is the code:
private void PhoneApplicationPage_BackKeyPress(object sender, CancelEventArgs e)
{
base.OnBackKeyPress(e);
this.player.Pause();
var result = MessageBox.Show(AppResources.GamePageAlert, "Warning", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
//NavigationService.RemoveBackEntry();
//App.RootFrame.Navigate(new Uri(#"/MainPage.xaml", UriKind.Relative));
}
else
{
this.player.Play();
e.Cancel = true;
}
}
However, I encoountered a big problem here I can't really solve. When I move back to MainMEnu, than go again to GenreSelectPage and choose the same genre, everything is ok - the app navigates to GamePage where there is list of 4 answers. However, if I choose another genre, the listBox at GamePage is populated with 12 or 15 items. On the other hand, when I comment navigation to MainPage and normally go back, everything works alright.
Here is my GenrePage Code:
public GenresPage()
{
InitializeComponent();
this.DataContext = App.ViewModel.GenreHelper;
}
private async void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
this.genresListBox.SelectedIndex = -1;
this.progressBar.Visibility = System.Windows.Visibility.Visible;
this.genresListBox.ItemsSource = await App.ViewModel.GenreHelper.GetGenres();
this.progressBar.Visibility = System.Windows.Visibility.Collapsed;
ClearCollections();
}
private static void ClearCollections()
{
if (App.ViewModel.TracksCollection.Count != 0)
{
App.ViewModel.TracksCollection.Clear();
App.ViewModel.TrackCounter = 0;
}
if (App.ViewModel.AnswerCollection.Count > 0)
{
App.ViewModel.AnswerCollection.Clear();
}
}
private async void NavigateToPlay(object sender, RoutedEventArgs e)
{
if (this.genresListBox.SelectedIndex != -1)
{
this.progressBar.Visibility = System.Windows.Visibility.Visible;
await App.ViewModel.GetSongs();
await App.ViewModel.GetAnswers();
this.progressBar.Visibility = System.Windows.Visibility.Collapsed;
NavigationService.Navigate(new Uri(#"/Views/GamePage.xaml", UriKind.Relative));
}
}
UPDATE
On my GamePage I am only assigning DataContext and duration to MediaElement:
public partial class GamePage : PhoneApplicationPage
{
public GamePage()
{
InitializeComponent();
this.DataContext = App.ViewModel;
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
var trackId = App.ViewModel.TracksCollection[App.ViewModel.TrackCounter].Id;
var sampleUri = App.ViewModel.GetSampleUri(trackId);
player.Source = new Uri(sampleUri.AbsoluteUri);
player.Play();
}
private void GetTrackDuration(object sender, RoutedEventArgs e)
{
var player = (MediaElement)sender;
if (player.CurrentState == System.Windows.Media.MediaElementState.Playing)
{
playerSeekBar.Maximum = player.NaturalDuration.TimeSpan.TotalSeconds;
}
}
private void PhoneApplicationPage_BackKeyPress(object sender, CancelEventArgs e)
{
base.OnBackKeyPress(e);
this.player.Pause();
var result = MessageBox.Show(AppResources.GamePageAlert, "Warning", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
//NavigationService.RemoveBackEntry();
//App.RootFrame.Navigate(new Uri(#"/MainPage.xaml", UriKind.Relative));
}
else
{
this.player.Play();
e.Cancel = true;
}
}
}
If anyone can point out what I am doing wrong, I would be really greatful - I am fighting it all day and I have no idea what's causing it.
Thank You very much in advance!!

WP8 issue with html agility pack

This is the function I used to get the string content from the website ..the problem is when executed first I cannot get the string content (App.Data2 = userprofile.InnerText;) since it skips to the next line (App.savecontent(App.Data2);) so that I get an empty string. If I recall the function I could get the string. Is there any possibility to solve this issue I need the string value first time automatically
This is my Page.cs code :
namespace Project_Future1
{
public partial class Page1 : PhoneApplicationPage
{
public Page1()
{
InitializeComponent();
{
string url = "http://www.astrosage.com/horoscope/daily-";
HtmlWeb.LoadAsync(url + App.Data + "-horoscope.asp", DownLoad);
}
data();
App.loadContent();
change2();
}
public void change2()
{
try
{
Util.LiveTile.UpdateLiveTile(App.Data2);
}
catch (Exception)
{
}
}
public void DownLoad(object sender, HtmlDocumentLoadCompleted e)
{
if (e.Error == null)
{
HtmlDocument doc = e.Document;
if (doc != null)
{
var userprofile = doc.DocumentNode.SelectSingleNode("//div[#class = 'ui-large-content']");
App.Data2 = userprofile.InnerText;
App.savecontent(App.Data2);
}
}
}
private void data()
{
SelectedSign.Text = App.Data;
SSContent.Text = App.Data2;
}
private void Refresh_click(object sender, EventArgs e)
{
SSContent.Text = App.Data2;
}
private void Fb_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/FB.xaml", UriKind.Relative));
}
}
}
this is my App.Xaml.cs File :
public static void savecontent(string save)
{
try
{
if (!string.IsNullOrEmpty(appFileName1))
{
IsolatedStorageFile oIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
oIsolatedStorage.CreateDirectory(appFolder1);
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream(appFolder1 + "\\" + appFileName1, FileMode.OpenOrCreate, oIsolatedStorage));
writeFile.WriteLine(save);
writeFile.Close();
}
}
catch (Exception)
{
throw;
}
}
this is my code to load the content from the storage :
public static void loadContent()
{
IsolatedStorageFile oIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (oIsolatedStorage.DirectoryExists(appFolder1))
{
IsolatedStorageFileStream fileStream = oIsolatedStorage.OpenFile(appFolder1 + "\\" + appFileName1, FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(fileStream))
{
App.Data2 = reader.ReadLine();
reader.Close();
}
}
}

Future get() gets nullpointer exeception in java

I'm implementing a function that detects if there is a webcam. This piece of code works fine in windows and I had no problem with it in linux centos OS. Now I'm trying to run the same code in Ubuntu, here an exception is thrown.
Exception in thread "main" java.lang.NullPointerException
at CameraProperties.CheckForCameraPlugin.check(CheckForCameraPlugin.java:51)
at Main.Main.main(Main.java:39)
The code is given below.
public boolean check()
{
boolean b = true;
service = Executors.newFixedThreadPool(1);
task = service.submit(new InitialCameraChecker());
try
{
final String str;
// waits the 10 seconds for the Callable.call to finish.
str = task.get();
if (str.matches("nodevice"))
{
b = false;//Return false if no camera device found
}
else
{
b = true;
}
}
catch (InterruptedException | ExecutionException ex)
{
msgbox.showJoptionPane(15);
}
service.shutdownNow();
return b;
}
The callable class is given below
class InitialCameraChecker implements Callable<String>
{
private List<Integer> devices = new ArrayList<Integer>();
private final static String VERSION_ID = "1.0.0";
private String res;
//Checking for the Camera
public String call()
{
try
{
loadWebcam();
discoverDevices();
if (devices.isEmpty())
{
res = "nodevice";//No we cam device found
}
else
{
res = "founddevice";//Found Web Cam Device
}
}
catch (Exception ex)
{
System.out.println("Exception_logout" + ex.toString());
}
return res;
}
//Discovering the camera device
private void discoverDevices()
{
for (int i = 0; i < 10; i++)
{
CvCapture cap = null;
try
{
cap = cvCreateCameraCapture(i);
int res = cvGrabFrame(cap);
if (res > 0)
{
devices.add(i);
break;
}
}
catch (Exception e)
{
System.out.println("Exception in camaracheck Thread1");
}
finally
{
if (cap != null)
{
try
{
cvReleaseCapture(cap.pointerByReference());
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
}
//Loading the dlls for starting the camera
private void loadWebcam()
{
String tmpDir = System.getProperty("java.io.tmpdir");
File faPath = new File(tmpDir + File.separator + "WebcamApplet_" + VERSION_ID.replaceAll("\\.", "-"));
System.setProperty("jna.library.path", faPath.getAbsolutePath());
}
}
Please tell me what is the problem. This works fine in windows.