How to play mp3 file from relative folder? - wpf

I tried to play a mp3 file from relative folder. I defined xaml look like.
<MediaElement x:Name="background_Sound" Source="\Music\Background_sound.mp3" LoadedBehavior="Pause" Volume="0.3" />
I want to play this file when the form open:
public MainWindow()
{
InitializeComponent();
background_Sound.LoadedBehavior = MediaState.Play;
}
But nothing happens.
I tried full path other mp3 Source = "E:\test.mp3", it worked well.
I tried to find more solutions from internet. Can you give me your advance.
Thank you so much.

Make sure that
the MP3-File is located in a folder named Music in your Visual Studio Project
its Build Action is set to Content
the Copy to Output Directory option is set to Copy always or Copy if newer
Then load the file by a valid relative path URI, without a leading \.
<MediaElement Source="Music\Background_sound.mp3" .../>
Alternative URIs are ".\Music\Background_sound.mp3" or "Music/Background_sound.mp3" or "./Music/Background_sound.mp3"

Related

Playing Background Music From Bundled File in Codenameone

I'm trying to have a background sound play in codenameone from an mp3 file that's packaged with the app (beep-07.mp3 is just in the src folder).
I can make it work using MediaManager.createMedia, with code borrowed from this post: How to bundle sounds with Codename One?
But the MediaManager.createBackgroundMedia function only takes in a uri, so I try using MediaManager.createBackgroundMedia("file://beep-07.mp3"); but no sound plays.
Am I doing something wrong in the file string?
The src directory doesn't exist on the device. The files that are there are packaged as resources into the equivalent of a jar. So you need to extract them if you want a URL. Notice this might work with "jar://beep-07.mp3" but I'm not sure.
A more correct approach would be to extract it from the jar on first use then use this URL (the code below assumes static import of the CN class):
String fileName = getAppHomePath() + "beep-07.mp3";
if(!existsInFileSystem(fileName)) {
try(InputStream i = getResourceAsStream("/beep-07.mp3");
OutputStream o = openFileOutputStream(fileName)) {
copy(i, o);
}
}
Media m = MediaManager.createBackgroundMedia(fileName);
FYI since your app is running you don't need background media only foreground media.

Visual Studio 2010 Project - can't adjust the relative path

I have a Windows Forms project. I have a Resources folder and I wan to use the files there using relative path. Here is a printscreen of my project tree
As you may see I have folder UserControls where I have FileExplorer.cs it contains aa openFileDialog + pictureBox. I use this control in some of my forms which are in Forms folder. The case is that in Resources folder I have this T380.jpg image that I want to load by default but for now I can do it only by inserting the full path to it. Here is my code where I try to load the image:
private void FileExplorer_Load(object sender, EventArgs e)
{
pictureBox1.ImageLocation = #"ShoesUnlimitedAdmin\Resources\T380.jpg";
pictureBox1.Load();
}
I use the Load event of the user control to load my image but it only works when I set the full path to the image like C:\\... and so. How can I point to the Resources folder of the project using relative path?
If these images are small then favor adding them as resources in the executable file so you can use Properties.Resources in your code and don't have to deploy the files on the user's machine. Use Project + Properties, Resources. Click the arrow on the "Add Resource" button and select Add Existing File.
If they are big (more than a couple of megabytes) then you'll indeed want to deploy them as separate files. You can find them back by using the location of the EXE program, here's a helper method, spelled out for clarity:
public static string GetResourcePath(string filename) {
string exepath = System.Reflection.Assembly.GetEntryAssembly().Location;
string exedir = System.IO.Path.GetDirectoryName(exepath);
string resdir = System.IO.Path.Combine(exedir, "Resources");
return System.IO.Path.Combine(resdir, filename);
}

WPF Dispay image from relative location

I would like to display an image on my dialog which could be located in a directory relative to the one the .exe is located in, e.g.
project
- data
-- logo //<-- that's where the image is located
-bin //<-- that's where the .exe is in
A default image should be included in the .exe but on displaying the dialog, the \data\logo directory should be checked first and if an image with the given filename could be found there that one should be used for display instead of the one that is inside the .exe.
Any ideas on how to do this?
Thanks,
tabina
Use the pack URI
pack://application:,,,/ReferencedAssembly;component/data/logo/image.png
As he asks for a folder relative to the exe, i suggest he means the logo should be located inside the filesystem (e.g. c:\program files\MyApp\data\logo). So I would check if the file exists with
File.Exists("/data/logo/logo.png")
If it returns false, you could load your embedded resource.
//Edit
If you use this snippet in your Visual Studio IDE the path is located at
<Project directory>/bin/debug/data/logo
what I am doing now is
// set the logo
string path = Environment.CurrentDirectory + "\\data\\logo\\logo.gif";
var uri = new Uri(path, UriKind.Absolute);
try
{
this.myImg.Source = new BitmapImage(uri);
}
catch (Exception e)
{
this.myImg.Source = new BitmapImage(new Uri(#"pack://application:,,,/myAssemblyName;component/Images/logo.gif"));
}
This works pretty well, but what I don't like about this is that it is all written in the code-behind. I would rather have it more re-usable.
Is there a way to put it all into a template and apply it to viewboxes/images?
Thanks,
tabina

How to access downloaded sound in IsolatedStorage via URI (WP7)?

I basically downloaded a file name custom.mp3 into my isolatedstorage and I can see it via isolatedstorage explorer....
The question here is... How can I access the particular custom.mp3 via URI?
So far I got this.. but I wonder why it is not working:
alarm.Sound = new Uri("isostore:/custom.mp3", UriKind.Absolute);
Your path is wrong. Nothing else is wrong with your code. Post the code you're using for saving the mp3 file in the first place, if you want further help.
For easier reading, the code to store the MP3 goes something like this..
string alarmfile = "custom.mp3";
isolatedStorageFileStream = new IsolatedStorageFileStream(alarmfile,FileMode.Create,isolatedStorageFile);
long songfilelength = (long) e.Result.Length;
byte[] songbyte = new byte[songfilelength];
e.Result.Read(songbyte, 0, songbyte.Length);
isolatedStorageFileStream.Write(songbyte, 0, songbyte.Length);
isolatedStorageFileStream.Flush();
Only files packaged in the XAML can be used as alarm sound:
Remarks
The Sound URI must point to a file packaged in the application’s .xap
file. Isolated storage is not supported. When the alarm is launched,
the sound is played quietly and then gradually increases in volume.
There is no way to modify this behavior.
From:
Alarm.Sound Property

WPF - Image 'is not part of the project or its Build Action is not set to Resource'

I have a project which requires an image in the window. This is a static image and i added through 'Add>Existing Item'. It exists in the root of the project.
I reference the image in a test page like so -
<Page x:Class="Critter.Pages.Test"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Test">
<Image Source="bug.png"/>
</Page>
Problem is I get a message saying it can't be found or it's build action isn't resource but it DOES exist and it's build action IS resource. If i create a new application and just throw it on a window then it works fine.
Any help would be great.
Try doing a full rebuild, or delete the build files and then build the file.
Visual Studio doesn't always pick up changes to resources, and it can be a pain to get it recompile.
Also try using a full URI as that helped me when I had the same problem. Something like
pack://application:,,,/MyAssembly;component/bug.png
→ Right click the image file
→ Click property
→ Select Build Action to Resource
→ Clean and Build solution
→ Run the Solution
You will get the all.
I had the same issue. Cleaning and rebuilding the solution didn't fix it so I restarted visual studio and it did. Here's hoping Visual 2010 fixes this issue and the many others that plauge wpf in Visual 2008.
Try starting the path to your image with a "/":
<Image Source="/bug.png"/>
There is a solution to your question
<Image Source="/WpfApplication4;component/images/sky.jpg" />
"component" is not a folder!
It doesn't, or at least the current beta doesn't. I found this page while looking into exactly the same problem. Rebuild/clean did nothing. After closing down and reloading the solution the file magically became compatible again.
I faced the exact same issue but restarting VS2008 or cleaning and rebuilding the project did not work for me. In the end, the below steps did the trick.
In Windows Explorer copy the Image into your project resource folder. Example: MyProject\Resources\
From within Visual Studio right click on the Resources and select "Add > Existing item" and select the image which you have just copied in
From within the form XAML set the image source as: "Source="Resources/MyImage.ico" (my image was saved as icon (.ico) file, but this approach should work for any image type
Hope this helps someone
Example of async load, another option. Example clip.mp4 is in the web project root.
void Landing_Loaded(object sender, RoutedEventArgs e)
{
//Load video async
Uri pageUri = HtmlPage.Document.DocumentUri;
Uri videoUri = new UriBuilder(pageUri.Scheme, pageUri.Host, pageUri.Port, "clip.mp4").Uri;
WebClient webClient = new WebClient();
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
webClient.OpenReadAsync(videoUri);
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
byte[] VideoBuffer = new byte[e.Result.Length];
e.Result.Read(VideoBuffer, 0, (int)e.Result.Length);
MemoryStream videoStream = new MemoryStream(VideoBuffer);
ContentVideo.SetSource(videoStream);
ContentVideo.Stop();
ContentVideo.Play();
}
I had a similar problem. After I deleted a someStyle.xaml file that I wasn't really using from the solution explorer.
Then I restored the file, but no change happened. Cleaning and rebuilding the project did not help.
Simply deleting the corresponding row:
<ResourceDictionary Source="someStyle.xaml"/>
did the trick.
I had the same error message but my issues was a simple NOOB mistake.
When I added my .ico files to "My Project / Resources", VS made a sub folder named Resources and I was trying to use;
<Window Icon="icons1.ico">
when I should have been using;
<Window Icon="Resources/icons1.ico">
... don't judge, I started using WPF 1 week ago :)

Resources