Save recorded sound to project file in UWP - c#

I recorded sound with the device's microphone but I don't know how to save it. Is it with the help of MediaCapture element, and if yes, then how to do it?

Here is a basic idea how to convert to mp3 and save in a file with Datawriter.
I wrote this code on the fly so its not tested.
MediaEncodingProfile _Profile = Windows.Media.MediaProperties.MediaEncodingProfile.CreateMp3(AudioEncodingQuality.High);
MediaTranscoder _Transcoder = new Windows.Media.Transcoding.MediaTranscoder();
CancellationTokenSource _cts = new CancellationTokenSource();
private void ConvertSteamToMp3()
{
IRandomAccessStream audio = buffer.CloneStream(); //your recoreded InMemoryRandomAccessStream
var folder = KnownFolders.MusicLibrary.CreateFolderAsync("MyCapturedAudio", CreationCollisionOption.OpenIfExists);
outputFile = await folder.CreateFileAsync("record.mp3", CreationCollisionOption.GenerateUniqueName);
using (IRandomAccessStream fileStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
{
var preparedTranscodeResult = await _Transcoder.PrepareStreamTranscodeAsync(audio, fileStream, _Profile);
if (preparedTranscodeResult.CanTranscode)
{
var progress = new Progress<double>(TranscodeProgress);
await preparedTranscodeResult.TranscodeAsync().AsTask(_cts.Token, progress);
}
using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))
{
using (DataWriter dataWriter = new DataWriter(outputStream))
{
//TODO: Replace "Bytes" with the type you want to write.
dataWriter.WriteBytes(bytes);
await dataWriter.StoreAsync();
dataWriter.DetachStream();
}
await outputStream.FlushAsync();
}
}
}
Or just save the stream in a file
public async SaveToFile()
{
IRandomAccessStream audio = buffer.CloneStream(); //your recoreded InMemoryRandomAccessStream
var folder = KnownFolders.MusicLibrary.CreateFolderAsync("MyCapturedAudio", CreationCollisionOption.OpenIfExists);
outputFile = await folder.CreateFileAsync("record.mp3", CreationCollisionOption.GenerateUniqueName);
using (IRandomAccessStream fileStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
{
await RandomAccessStream.CopyAndCloseAsync(audio.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));
await audio.FlushAsync();
audio.Dispose();
}
});
}

Related

How to save SpeechSynthesis audio to a Mp3 file in a UWP application

I'm working on a UWP TTS (Text to Speech) application and I'm having trouble saving speech to a file, preferably in Mp3 format. Does anyone know how to do this? In WPF, I used NAUDIO and NAUDIO.LAME, but unfortunately this does not seem to support UWP. I think I have to use Windows.Media.Transcoding API, but I didn't find any examples of how to do that. I found the code below in an article on MSDN, but it is not correct.
StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
try
{
SpeechSynthesisStream stream = await WCSVariables.Synthesizer.SynthesizeTextToStreamAsync(rtbText.Text);
using (var reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
IBuffer buffer = reader.ReadBuffer((uint)stream.Size);
await FileIO.WriteBufferAsync(file, buffer);
}
}
catch (Exception ex)
{
MessageDialog msgdlg = new MessageDialog(ex.Message);
msgdlg.ShowAsync();
}
********** UPDATE **********
After adding capabilities and file type associations for TXT and MP3, I was able to save the TXT files in any folder, but the MP3 files do not have the correct format. Files are created but do not play audio.
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
savePicker.FileTypeChoices.Add("Mp3 Audio File", new List<string>() { ".mp3" });
savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
savePicker.SuggestedFileName = "New Document";
StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
try
{
if (file.FileType == ".txt")
{
await FileIO.WriteTextAsync(file, rtbText.Text);
}
else
{
string path = file.Path.Remove(file.Path.IndexOf(file.Name), file.Name.Length);
StorageFolder mp3Folder = await StorageFolder.GetFolderFromPathAsync(path);
StorageFile mp3File = await mp3Folder.CreateFileAsync(file.Name, CreationCollisionOption.ReplaceExisting);
SpeechSynthesisStream stream = await WCSVariables.Synthesizer.SynthesizeTextToStreamAsync(rtbText.Text);
using (var reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
IBuffer buffer = reader.ReadBuffer((uint)stream.Size);
await FileIO.WriteBufferAsync(mp3File, buffer);
}
}
}
catch (Exception ex)
{
MessageDialog msgdlg = new MessageDialog(ex.Message);
msgdlg.ShowAsync();
}
}
You can first create a .mp3 file and then generate a speech audio stream from a basic text string. After that, write the stream to the file.
StorageFolder folder = KnownFolders.VideosLibrary;
StorageFile file = await folder.CreateFileAsync("MyVideo.mp3",CreationCollisionOption.ReplaceExisting);
if (file != null)
{
try
{
var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync("Hello World");
using (var reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
IBuffer buffer = reader.ReadBuffer((uint)stream.Size);
await FileIO.WriteBufferAsync(file, buffer);
}
}
catch {}
}

UWP BitmapEncoder close file?

How can I finalize/close the BitmapEncoder on UWP?
InMemoryRandomAccessStream imras = new InMemoryRandomAccessStream();
await [...] //Fill stream
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(imras);
[...] //Do something
StorageFile sf = await ApplicationData.Current.LocalFolder.CreateFileAsync("123.jpg", CreationCollisionOption.ReplaceExisting);
BitmapEncoder bmpEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, await sf.OpenAsync(FileAccessMode.ReadWrite));
[...]
await bmpEncoder.FlushAsync();
imras.Dispose();
Now when I try to access the file, I get a System.UnauthorizedAccessException, I have to close the UWP app to be able to access this file... How can I close it?
You need to dispose every IDisposable object. The easiest way is to use using keyword.
using (var stream = await storageFile.OpenAsync()) // Or any other method that will open a stream.
{
var bitmapDecoder = await BitmapDecoder.CreateAsync(stream);
using (var randomAccessStream = new InMemoryRandomAccessStream())
{
var bitmapEncoder = await BitmapEncoder.CreateForTranscodingAsync(randomAccessStream, bitmapDecoder);
// Do stuff.
await bitmapEncoder.FlushAsync();
var buffer = new byte[randomAccessStream.Size];
await randomAccessStream.AsStream().ReadAsync(buffer, 0, buffer.Length);
var someNewFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("SomeFileName", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteBytesAsync(someNewFile, buffer);
}
}

How to download and store an image using Windows.Web.Http?

How do I download and store a jpeg image from the internet in a Windows Store App with Windows.Web.Http?
The problem that I am facing is that I don't know what Get…Async and Write…Async method I must use for an image? It is very different with files, than with strings.
Only Windows.Web.Http!
No third-party solutions!
If you suggest something else, please use the comment section, not the answer. Thank you!
…
using Windows.Storage;
using Windows.Web.Http;
Uri uri = new Uri("http://image.tmdb.org/t/p/w300/" + posterPath);
HttpClient httpClient = new HttpClient();
// I guess I need to use one of the Get...Async methods?
var image = await httpClient.Get…Async(uri);
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFolder cachedPostersFolder = await localFolder.CreateFolderAsync("cached posters", CreationCollisionOption.OpenIfExists);
StorageFile posterFile = await cachedPostersFolder.CreateFileAsync(posterPath, CreationCollisionOption.ReplaceExisting);
// I guess I need to use one of the Write...Async methods?
await FileIO.Write…Async(posterFile, image);
You can get a buffer using the GetBufferAsync method and then call the FileIO.WriteBufferAsync to write the buffer to a file:
Uri uri = new Uri("http://i.stack.imgur.com/ZfLdV.png?s=128&g=1");
string fileName = "daniel2.png";
StorageFile destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
fileName, CreationCollisionOption.GenerateUniqueName);
HttpClient client = new HttpClient();
var buffer = await client.GetBufferAsync(uri);
await Windows.Storage.FileIO.WriteBufferAsync(destinationFile, buffer);
image1.Source = new BitmapImage(new Uri("http://www.image.com/image.jpg", UriKind.RelativeOrAbsolute));
using (var mediaLibrary = new MediaLibrary())
{
using (var stream = new MemoryStream())
{
var fileName = string.Format("Gs{0}.jpg", Guid.NewGuid());
bmp.SaveJpeg(stream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
stream.Seek(0, SeekOrigin.Begin);
var picture = mediaLibrary.SavePicture(fileName, stream);
if (picture.Name.Contains(fileName)) return true;
}
}
This is a similar answer to John's, however in WP8.1 you can't use GetBufferAsync. Instead you can use GetStreamAsync in the way that I have:
Uri uri = new Uri(UriString);
string fileName = p4.IconLocation;
HttpClient client = new HttpClient();
var streamImage = await client.GetStreamAsync(uri);
await SaveToLocalFolderAsync(streamImage, fileName);
using the function:
public async Task SaveToLocalFolderAsync(Stream file, string fileName)
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile storageFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (Stream outputStream = await storageFile.OpenStreamForWriteAsync())
{
await file.CopyToAsync(outputStream);
}
}

Save .mp4 to Windows Phone video library

I was wondering how I can download an MP4 video file from a URI and save it to the media library on Windows Phone 8.1.
It would be great if it worked in a Universal App - but it doesn't have to.
I found this code to save an image to the camera roll - do I go the same way about this with an *.mp4 to save it to the video library? And can I just hand off a download stream (not sure if that makes sense) to that function?
StorageFolder testFolder = await StorageFolder.GetFolderFromPathAsync(#"C:\test");
StorageFile sourceFile = await testFolder.GetFileAsync("TestImage.jpg");
StorageFile destinationFile = await KnownFolders.CameraRoll.CreateFileAsync("MyTestImage.jpg");
using (var sourceStream = await sourceFile.OpenReadAsync())
{
using (var sourceInputStream = sourceStream.GetInputStreamAt(0))
{
using (var destinationStream = await destinationFile.OpenAsync(FileAccessMode.ReadWrite))
{
using (var destinationOutputStream = destinationStream.GetOutputStreamAt(0))
{
await RandomAccessStream.CopyAndCloseAsync(sourceInputStream, destinationStream);
}
}
}
}
So I finally figured it out, this is what my code looks like:
var httpClient = new HttpClient();
var response = await httpClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var file = await response.Content.ReadAsByteArrayAsync();
StorageFile destinationFile
= await KnownFolders.SavedPictures.CreateFileAsync("file.mp4",
CreationCollisionOption.ReplaceExisting);
Windows.Storage.Streams.IRandomAccessStream stream = await destinationFile.OpenAsync(FileAccessMode.ReadWrite);
IOutputStream output = stream.GetOutputStreamAt(0);
DataWriter writer = new DataWriter(output);
writer.WriteBytes(file);
await writer.StoreAsync();
await output.FlushAsync();
}

Write (Read) IO.Stream to (from) ApplicationData.Current.LocalFolder

What is the best way to read amnd write and IO.Stream (Zip file downloded from internet in my case) to ApplicationData.Current.LocalFolder
I tried
public static async Task WriteToFile(
this System.IO.Stream input,
string fileName,
StorageFolder folder = null)
{
folder = folder ?? ApplicationData.Current.LocalFolder;
var file = await folder.CreateFileAsync(
fileName,
CreationCollisionOption.ReplaceExisting);
using (var fs = await file.OpenAsync(FileAccessMode.ReadWrite))
{
using (var outStream = fs.GetOutputStreamAt(0))
{
using (var dataWriter = new DataWriter(outStream))
{
byte[] buffer = new byte[8 * 1024];
int len;
while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
{
dataWriter.WriteBytes(buffer);
}
await dataWriter.StoreAsync();
dataWriter.DetachStream();
}
await outStream.FlushAsync();
}
}
}
for writing and
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);
var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
var stream = fileStream.AsStreamForRead();
but the file gets corrupted somewhere along the way.I do no think there is a problem with reading so it should be somewhere in writing the file. Is there a better way to write IO.Stream to ApplicationData.Current.LocalFolder that works?
Try this:
static async void DownloadFileAsync(
this HttpClient httpClient,
string requestUri,
string fileName,
StorageFolder folder = null)
{
folder = folder ?? ApplicationData.Current.LocalFolder;
var file = await folder.CreateFileAsync(
fileName, CreationCollisionOption.ReplaceExisting);
using (var httpStream = await httpClient.GetStreamAsync(uri))
using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
await httpStream.CopyToAsync(fileStream.AsStreamForWrite());
}
}
MSDN: Http­Client Class, Http­Client.­Get­Stream­Async Method, Windows­Runtime­Stream­Extensions.­As­Stream­For­Write Method, Stream.­Copy­To­Async Method.

Categories

Resources