Trouble pathing an audio file using WMPLib - c#

I'm new to C# and pathing files have troubled me for a while.
The file structure to the audio files is as follows:
C:\Users\Username\Documents\Program\Form\WindowsFormApp\Audio Files\name.mp3
My visual studio forms are in:
C:\Users\Username\Documents\Program\Form\WindowsFormApp
I tried referencing audio files by using the following URL:
soundplayer.URL = #"Audio Files\name.mp3";
However, that did not work.
I then placed the folder Audio Files inside practically every other folder. It still did not work.
I tried:
soundplayer.URL = #"..\\Audio Files\name.mp3";
That did not work as well. I cannot simply do the entire path of the audio because it is different on each computer.
How do I path this correctly?

Well, in your case, it would be as follows
using System.IO;
using WMPLib;
WindowsMediaPlayer player;
private void button1_Click(object sender, EventArgs e)
{
string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), #"Audio Files\name.mp3");
player = new WindowsMediaPlayer();
FileInfo fileInfo = new FileInfo(path);
player.URL = fileInfo.Name;
player.controls.play();
}
Where
//This function gets the current route of your project and combines it with the subfolder path where your music file is
string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), #"Audio Files\name.mp3");

Related

Store and read csv file from android and ios in Unity

I have a Unity project which I want to work for both android and ios. I also have a csv file which I want to read during runtime. I tried the following code:
string basePath = Path.Combine(Application.persistentDataPath, $"{fileName}.csv");
if (File.Exists(basePath))
{
string[] rows = File.ReadAllLines(basePath);
foreach (string item in rows)
{
Debug.Log(item);
}
}
However, I don't know where to put the csv file for it to find it on persistentDataPath. And if I find the correct place, will it be the same on android and ios or do I need to save the file on more locations or folders?
Or do you have any other suggestions on how to store and then load a cvs for different platforms?
If you just want to read a .csv file that you deploy with your game, you could just place it into the Resources folders inside your Assets.
You could read it like this:
TextAsset file = Resources.Load(fileName) as TextAsset;
string content = file.ToString();
Note: fileName must be specified here without file extension.
If you want to modify the .csv file or perhaps make it available in Application.persistentDataPath, you can simply copy it to that location first. For later changes you can then access the file in persistentDataPath.
Self-Contained Example
A self-contained example could look something like this:
using System.IO;
using UnityEngine;
public class CSVFileManager : MonoBehaviour
{
void Start()
{
var fileName = "example";
var csvFileName = $"{fileName}.csv";
string basePath = Path.Combine(Application.persistentDataPath, csvFileName);
Debug.Log($"basePath = >>{basePath}<<");
if (!File.Exists(basePath))
{
TextAsset file = Resources.Load(fileName) as TextAsset;
string content = file.ToString();
File.WriteAllText(basePath, content);
}
else
{
//... work with the current file in persistentDataPath
}
}
}
Test
I tested it briefly on Mac, but it should work equally well on Android and iOS:

How to play a sound that was imported into C# WPF project?

I have an issue with trying to play sound in my WPF application. When I reference the sound from its actual file location, like this,
private void playSound()
{
//location on the C: drive
SoundPlayer myNewSound = new SoundPlayer(#"C:\Users\...\sound.wav");
myNewSound.Load();
myNewSound.Play();
}
it works fine. However, I recently imported the same sound into my project, and when I try to do this,
private void playSound()
{
//location imported in the project
SoundPlayer myNewSound = new SoundPlayer(#"pack://application:,,,/sound.wav");
myNewSound.Load();
myNewSound.Play();
}
it produces an error and the sound won't play. How can I play the sound file imported into my project?
Easiest/shortest way for me is to change Build Action of added file to Resource, and then just do this:
SoundPlayer player = new SoundPlayer(Properties.Resources.sound_file);//sound_file is name of your actual file
player.Play();
You are using pack Uri as argument, but it needs either a Stream or a filepath .
As you have added the file to your project, so change its Build Action to Content , and Copy To Output Directory to Always.
using (FileStream stream = File.Open(#"bird.wav", FileMode.Open))
{
SoundPlayer myNewSound = new SoundPlayer(stream);
myNewSound.Load();
myNewSound.Play();
}
You can do it with reflection.
Set the property Build Action of the file to Embedded Resource.
You can then read it with:
var assembly = Assembly.GetExcetutingAssembly();
string name = "Namespace.Sound.wav";
using (Stream stream = assembly.GetManifestResourceStream(name))
{
SoundPlayer myNewSound = new SoundPlayer(stream);
myNewSound.Load();
myNewSound.Play();
}

AXWindowsMediaPlayer not finding embedded resource MP3

I have a embedded resource file (MP3 to be exact) that plays a short boop. I wanted it for easy transport of the file since I have a lot more of them that I'm looking to add in.
When I try to play it, WMP just says it cannot find the file.
I'm using axWindowsMediaPlayer1.URL = #"ultraelecguitar.Properties.Resources.pitchedbeep"; to access it. It is added in the resource manager, and marked as a embedded resource. When I run my program with the file in the directory, it works just fine. When I don't, it doesn't work at all.
If you save resource as temporary file then you could provide it's path as url.
static void Main(string[] args)
{
var wmp = new WMPLib.WindowsMediaPlayer();
wmp.URL = CreateTempFileFromResource("ConsoleApplication1.mp3.somefile.mp3");
Console.ReadKey();
}
private static string CreateTempFileFromResource(string resourceName)
{
var tempFilePath = Path.GetTempFileName() + Path.GetExtension(resourceName);
using (var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
using (var tempFileStream = new FileStream(tempFilePath, FileMode.Create))
{
resourceStream.CopyTo(tempFileStream);
}
return tempFilePath;
}

Soundplayer for compiled application

How can I hardcode the code in order to pull the .wav file from the project?
As well as where should I put the .wav file?
The code I am currently using is:
private void timer2_Tick(object sender, EventArgs e)
{
SoundPlayer simpleSound = new SoundPlayer(#"c:\Windows\Media\dj.wav");
simpleSound.Play();
}
I just want the path #"c:\Windows\Media\dj.wav" to be for that content folder... So that when I deploy the application to another computer it comes with it....
Use GetManifestResourceStream.
var path = "MyApplicationNamespace.Content.dj.wav";
var assembly = Assembly.GetExecutingAssembly();
using( var soundStream = assembly.GetManifestResourceStream( path ) )
using( var soundPlayer = new SoundPlayer( soundStream ) )
{
soundPlayer.Play();
}
The string passed to GetManifestResourceStream must be fully qualified with your application's root namespace and the directory tree the wave file resides in.
You also need to set the Build Action for the wave file to Embedded Resource in the properties window.

How can I write to a specific location in Windows Phone 8

When I press a button, I want it to overwrite a file to a specific folder.
I use this code:
private void btnArial_Click(object sender, RoutedEventArgs e)
{
string cssDocument = "body{font-family:\"Arial\";}";
//I want to write file style.css to folder css inside html
string path = Package.Current.InstalledLocation.Path + "\\Html\\css\\style.css";
if (File.Exists(path))
{
StreamWriter writer = new StreamWriter(path);
writer.Write(cssDocument);
writer.Close();
}
changeStyle(new FontFamily("Arial"));
}
When I tested on emulator and actual devide, it worked properly.
But when I submit app to store, it got error - the app exits when I press that button.
The install directory (Package.Current.InstalledLocation) is a read-only location. Unfortunately, due to the way that Visual Studio optimizes development-time deployment, it is set to read-write when the app is deployed from VS. That's why you see a difference in behavior after you submit the app to the store.
If you need to modify a file in your install directory, you must first copy it over to a writeable location - eg. your Local folder.
I prefer using Isolated storage in WP8 to write files and it never fails. Also you can use Windows.Storage apis.
private async void MyButton_Click(object sender, RoutedEventArgs e)
{
string cssDocument = "body{font-family:\"Arial\";}";
// using Windows.Storage
StorageFolder folder = ApplicationData.Current.LocalFolder;
folder = await folder.CreateFolderAsync("HTML", CreationCollisionOption.OpenIfExists);
folder = await folder.CreateFolderAsync("CSS", CreationCollisionOption.OpenIfExists);
StorageFile file = await folder.CreateFileAsync("style.css", CreationCollisionOption.ReplaceExisting);
using (var writer = new StreamWriter(await file.OpenStreamForWriteAsync()))
{
writer.Write(cssDocument);
}
// using using System.IO.IsolatedStorage;
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!store.DirectoryExists("HTML/CSS"))
store.CreateDirectory("HTML/CSS");
using (var writer = new StreamWriter(store.OpenFile("HTML/CSS/style.css", FileMode.Create)))
{
writer.Write(cssDocument);
}
}
changeStyle(new FontFamily("Arial"));
}
Exactly..
Write the file in Isolated storage. Its easier and pretty straight forward. The files here can be accessed, viewed, modified, removed, replaced in a very clear way. I personally prefer the Isolated Storage.

Categories