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.
Related
I implemented audio implementation and added looping property also. But the audio Plays a two times only and after that audio doesn't play. Here I attached a code I implemented. Kindly help how to fix. Thanks for advance
namespace Com.Audio.Droid
{
public class AudioService : IAudio
{
public AudioService()
{
}
public void PlayAudioFile(string fileName)
{
var player = new MediaPlayer();
var fd = global::Android.App.Application.Context.Assets.OpenFd("siren.wav");
player.Prepared += (s, e) =>
{
player.Start();
};
player.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
player.Looping = true;
player.Prepare();
}
public void PauseAudioFile(string fileName)
{
Device.BeginInvokeOnMainThread(() =>
{
var player = new MediaPlayer();
var fd = global::Android.App.Application.Context.Assets.OpenFd("siren.wav");
player.Prepared += (s, e) =>
{
player.Stop();
player.Release();
player.Dispose();
};
player.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
player.Prepare();
});
}
}
}
And in iOS the audio play a only one second. It's doesn't play the audio file entirely
namespace com.Audio.ios
{
public class AudioService : IAudio
{
public AudioService()
{
}
public void PlayAudioFile(string fileName)
{
string sFilePath = NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension("siren"), Path.GetExtension("siren.wav"));
var url = NSUrl.FromString(sFilePath);
var _player = AVAudioPlayer.FromUrl(url);
_player.FinishedPlaying += (object sender, AVStatusEventArgs e) =>
{
_player = null;
};
_player.NumberOfLoops = -1;
_player.Play();
}
public void PauseAudioFile(string fileName)
{
string sFilePath = NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension("siren"), Path.GetExtension("siren.wav"));
var url = NSUrl.FromString(sFilePath);
var _player = AVAudioPlayer.FromUrl(url);
_player.FinishedPlaying += (object sender, AVStatusEventArgs e) =>
{
_player = null;
};
_player.Stop();
}
}
}
For Android
You need a hook way to implement a loopMediaPlayer, that is creating a new player when the audio is finished.
Refer to : https://stackoverflow.com/a/29883923/8187800 .
For iOS
Due to ARC , probably AVAudioPlayer is released after calling dependency service , to solved it you can try to make _player as global variable .
Refer to
https://stackoverflow.com/a/8415802/8187800 .
I'm trying to implement an app of news (feedrss) by using WP7 i've tried this solution , but it does'nt work for me , here is my code :
namespace PhoneApp1
{
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();}
private void Go_Click(object sender, RoutedEventArgs e)
{
WebClient _client = new WebClient();
_client.DownloadStringCompleted += Feed;
Location.Text = "http://www.aufaitmaroc.com/feeds/ma-vie.xml";
_client.DownloadStringAsync(new Uri((Location.Text)));
InitializeComponent();
}
private void Feed(object Sender, DownloadStringCompletedEventArgs e)
{
XElement _xml;
try
{
if (!e.Cancelled)
{
_xml = XElement.Parse(e.Result);
List<FeedItem> l = new List<FeedItem>();
foreach (XElement value in _xml.Elements("channel").Elements("item"))
{
FeedItem _item = new FeedItem();
_item.Title = value.Element("title").Value;
_item.enclosure = value.Element("enclosure").Attribute("url").Value;
_item.Description = Regex.Replace(value.Element("description").Value,
#"<(.|\n)*?>", String.Empty);
_item.Link = value.Element("link").Value;
_item.Guid = value.Element("guid").Value;
_item.Published = DateTime.Parse(value.Element("pubDate").Value);
l.Add(_item);
HttpWebRequest reqest1 = (HttpWebRequest)WebRequest.Create(_item.enclosure);
reqest1.BeginGetResponse(DownloadImageCallback, reqest1);
Thread.Sleep(1000);
WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri(_item.enclosure), client);
}
listBox.ItemsSource = l;
}
}
catch
{
}
}
IsolatedStorageFile MyStore = IsolatedStorageFile.GetUserStoreForApplication();
void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
var resInfo = new StreamResourceInfo(e.Result, null);
var reader = new StreamReader(resInfo.Stream);
byte[] contents;
using (BinaryReader bReader = new BinaryReader(reader.BaseStream))
{
contents = bReader.ReadBytes((int)reader.BaseStream.Length);
}
IsolatedStorageFileStream stream = MyStore.CreateFile("10.jpg");
stream.Write(contents, 0, contents.Length);
stream.Close();
}
void DownloadImageCallback(IAsyncResult result)
{
HttpWebRequest req1 = (HttpWebRequest)result.AsyncState;
HttpWebResponse responce = (HttpWebResponse)req1.EndGetResponse(result);
Stream s = responce.GetResponseStream();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
string directory = "Imagestest";
if (!MyStore.DirectoryExists(directory))
{
MyStore.CreateDirectory(directory);
IsolatedStorageFileStream stream = MyStore.CreateFile("10.jpg");
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var isoFileStream = myIsolatedStorage.CreateFile(directory + "//ANALYSE_10052013095620.jpg"))
{
var bitimage = new BitmapImage();
var wb = new WriteableBitmap(bitimage);
var width = wb.PixelWidth;
var height = wb.PixelHeight;
// bitimage.SetSource = isoFileStream;
image1.Source = bitimage;
System.Windows.Media.Imaging.Extensions.SaveJpeg(wb, isoFileStream, width, height, 0, 100);
}
}
}
else
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(directory + "//ANALYSE_10052013095620.jpg"))
{
myIsolatedStorage.DeleteFile(directory + "//ANALYSE_10052013095620.jpg");
}
using (var isoFileStream = myIsolatedStorage.CreateFile(directory + "//ANALYSE_10052013095620.jpg"))
{
var bitimage = new BitmapImage();
var wb = new WriteableBitmap(bitimage);
var width = wb.PixelWidth;
var height = wb.PixelHeight;
System.Windows.Media.Imaging.Extensions.SaveJpeg(wb, isoFileStream, width, height, 0, 100);
}
}
}
});
}
private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
FeedItem currentFeedItem = (FeedItem)listBox.SelectedItem;
PhoneApplicationService.Current.State["FeedItem"] = currentFeedItem;
}
When i run this project , nothing's happend , it does'nt create any folder ,when i stop the internet , images doesnt display anymore.
If you need image caching in your app, I can suggest JetImageLoader library for you
Features:
Caching in memory (so it will work very fast with lists, grids, etc)
Caching is IsolatedStorageFile (to prevent reloading each time)
Fully asynchronous (no lags)
Usage via XAML Binding Converter, you do not have to change your code, just declare converter for Image
But it supports only Windows Phone 8+
I am authour of that library, so if you got any questions, please write to me here or create an issue on github
If you want to save image locally and the display image from locally, then try this sample
http://code.msdn.microsoft.com/wpapps/CSWP8ImageFromIsolatedStora-8dcf8411, on WP 8 it's works fine.
I am trying to re size the data grid view in windows form. There are two data grid view on my form and both are fed from the database. Is there any was I can resize the data grid view on the left so that it grows with the content length and width and the data grid view shrinks with the content.
Given below is my code
private void show_Click(object sender, EventArgs e)
{
int rowIndex = Convert.ToInt32(productGridView.SelectedRows[0].Cells[2].Value);
//IEnumerable<Supplier> supplierQuery = from supplier in newNorthWindContext.Suppliers
// where supplier.SupplierID == rowIndex
// select new {} supplier;
IEnumerable<Supplier> supplierQuery = newNorthWindContext.Suppliers.Where(supliers => supliers.SupplierID == rowIndex);
supplierDataGridView.DataSource = ((ObjectQuery)supplierQuery).Execute(MergeOption.AppendOnly);
supplierDataGridView.Columns["SupplierID"].Visible = false;
supplierDataGridView.Columns["ContactTitle"].Visible = false;
supplierDataGridView.Columns["Address"].Visible = false;
supplierDataGridView.Columns["City"].Visible = false;
supplierDataGridView.Columns["Region"].Visible = false;
supplierDataGridView.Columns["PostalCode"].Visible = false;
supplierDataGridView.Columns["ContactTitle"].Visible = false;
supplierDataGridView.Columns["Address"].Visible = false;
//supplierDataGridView.AutoResizeColumns();
supplierDataGridView.AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode.AllCells;
}
private void categoryDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
Category category = (Category)this.categoryDropDown.SelectedItem;
try
{
productGridView.DataSource = category.Products;
productGridView.Columns["SupplierID"].Visible = false;
productGridView.Columns["CategoryID"].Visible = false;
productGridView.Columns["Category"].Visible = false;
productGridView.Columns["Order_Details"].Visible = false;
productGridView.Columns["Supplier"].Visible = false;
productGridView.AllowUserToDeleteRows = true;
productGridView.AutoResizeColumns();
productGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ProductDetail_Load(object sender, EventArgs e)
{
newNorthWindContext = new NorthwindEntities();
productGridView.AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode.AllCells;
IEnumerable<Category> categoryQuery = from category in newNorthWindContext.Categories.Include("Products")
orderby category.CategoryName
select category;
try
{
this.categoryDropDown.DataSource = ((ObjectQuery)categoryQuery).Execute(MergeOption.AppendOnly);
this.categoryDropDown.DisplayMember = "categoryName";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This solves the issue.
supplierDataGridView.Width = supplierDataGridView.Columns.GetColumnsWidth(DataGridViewElementStates.Visible)+4;
at the end of show_Click you should have something like
supplierDataGridView.Width = supplierDataGridView.Columns.Sum(x => x.Width) + supplierDataGridView.RowHeadersWidth + 2;
supplierDataGridView.Height = supplierDataGridView.GetRowDisplayRectangle(supplierDataGridView.NewRowIndex, true).Bottom + supplierDataGridView.GetRowDisplayRectangle(supplierDataGridView.NewRowIndex, false).Height;
I hope this helps!
I have a code where I am calling photochooser in WP7 and I want to show a messagebox to user when the pic is more than 2Mb. When I try to do this, since the photochooser task is running in background, we start getting unhandled exceptions.
void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.ChosenPhoto != null)
{
ProgressBar.Visibility = Visibility.Visible;
image = _UploadImgeViewModel.ReadToEnd(e.ChosenPhoto);
if (image.Length < 16384)
{
BitmapImage bi = new BitmapImage();
bi.SetSource(e.ChosenPhoto);
UserSession.ProfileImage = bi;
Session.PreviousImage = bi;
UserSession.isImageChanged = true;
UserSession.image = image;
UserSession.Uploadimage = image;
NavigationService.Navigated += new NavigatedEventHandler(navigateCompleted);
}
else
{
ProgressBar.Visibility = Visibility.Collapsed;
UserSession.isImageChanged = false;
UserSession.ProfileImage = null;
Dispatcher.BeginInvoke(() => MessageBox.Show("The message"));
}
}
}
#endregion
This only shows the background job as resuming... and the msg box in foreground. and after a few seconds, the app crashes.
Can you please help me with this?
Cool. I got some idea to resolve this. Might not be a fix, but this way we can avoid this issue. Just add a button and do the validating process in the button click event. Since we can't display the message box when the navigation is in progress.
Below is the code:
void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.ChosenPhoto != null)
{
ProcessSelectedImage(e.ChosenPhoto);
}
}
private void ProcessSelectedImage(Stream stream)
{
if (stream != null)
{
bi.SetSource(stream);
UserSession.ProfileImage = bi;
UserSession.PreviousImage = bi;
image = ConvertToImage.ReadToEnd(stream);
UserSession.image = image;
UserSession.Uploadimage = image;
}
}
private void UploadImage_Click(object sender, RoutedEventArgs e)
{
if (image.Length < 16384)
{
UserSession.isImageChanged = true;
UserSession.image = image;
UserSession.Uploadimage = image;
NavigationService.Navigate(new Uri("/Views/EditMyProfile.xaml", UriKind.Relative));
}
else
{
UserSession.isImageChanged = false;
UserSession.ProfileImage = null;
UserSession.IsChangingProfilePicture = true;
MessageBox.Show(MessageContent.ImageUploadLengh);
}
}
Thanks
Kamal
You have 10 seconds to return to the foreground completely or your app will be killed. If you have a messagebox that can display here, you will fail certification (because user could not click anything for 10 seconds) -- you need to wait for the page to load.
A workaround for this if you need to show a MessageBox is to set a bool, and check it in the Page's Loaded event.
void photoChooserTask_Completed(object sender, PhotoResult e) { if (e.ChosenPhoto != null) { ProgressBar.Visibility = Visibility.Visible;
image = _UploadImgeViewModel.ReadToEnd(e.ChosenPhoto);
if (image.Length < 16384)
{
BitmapImage bi = new BitmapImage();
bi.SetSource(e.ChosenPhoto);
UserSession.ProfileImage = bi;
Session.PreviousImage = bi;
UserSession.isImageChanged = true;
UserSession.image = image;
UserSession.Uploadimage = image;
NavigationService.Navigated += new NavigatedEventHandler(navigateCompleted);
}
else
{
ProgressBar.Visibility = Visibility.Collapsed;
UserSession.isImageChanged = false;
UserSession.ProfileImage = null;
//set flag
UserSession.ImageTooBig = true;
}
}
}
#endregion
MyPage()
{
//make sure you attach Loaded Event if not already
Loaded += (s,e) =>
{
if (UserSession.ImageTooBig)
{
UserSession.ImageTooBig = false;
MessageBox.Show("Sorry, the image exceeds 2 MB");
}
};
}
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>");