VS 2005 C++ edit content of the CRichEditCtrl instance - c++

I've installed a Windows XP Professional SP3 on a VMWare image and the Visual Studio 2005 on it. I've created a new dialog based C++ MFC project with /clr support. I've put a RichEdit 2.0 control onto the auto-generated dialog and I'm trying to read up a text file and put its content into this RichEdit 2.0 control by button click without formatting. I've added a variable to the RichEdit 2.0 called pCRichEditCtrl and here is my code which doesn't work.
CWinApp inheritance:
BOOL CTextFormatterApp::InitInstance()
{
...
AfxInitRichEdit2();
CWinApp::InitInstance();
...
}
CDialog inheritance:
void CTextFormatterDlg::OnBnClickedButton1()
{
StreamReader^ objReader = gcnew StreamReader("c:\\text.txt");
String ^sLine = "";
sLine = objReader->ReadLine();
while (sLine != nullptr)
{
pCRichEditCtrl.SetSel(pCRichEditCtrl.GetTextLength(), -1);
pCRichEditCtrl.ReplaceSel(CString(sLine));
sLine = objReader->ReadLine();
}
objReader->Close();
}
I don't know whether it counts but I get the following warnings at linking:
TextFormatterDlg.obj : warning LNK4248: unresolved typeref token (01000016) for 'AFX_CMDHANDLERINFO'; image may not run
TextFormatter.obj : warning LNK4248: unresolved typeref token (01000012) for 'AFX_CMDHANDLERINFO'; image may not run
TextFormatterDlg.obj : warning LNK4248: unresolved typeref token (01000015) for 'IAccessibleProxy'; image may not run
I'm not sure what I'm doing because I'm familiar only with newer frameworks and I don't know either Windows.
Input file exists, I can see the read text if I debug the application but I can't see any changes in the edit box. I've tried to call pCRichEditCtrl.UpdateData(true); but nothing has changed.
Is it enough to add a variable for getting the controller of the box (pCRichEditCtrl)? It seems to the pointer doesn't point to the proper control item.
Do you have any idea what is missing?

There's no need to use CLI to just read text files, try something like:
void CTextFormatterDlg::OnBnClickedButton1()
{ CStdioFile f1;
CString sLine;
if (!f1.Open(_T("c:\\text.txt"), CFile::modeRead | CFile::typeText))
return;
while (f1.ReadString(sLine))
{ pCRichEditCtrl.SetSel(pCRichEditCtrl.GetTextLength(), -1);
pCRichEditCtrl.ReplaceSel(sLine);
}
f1.Close();
}
EDIT: control variable pCRichEditCtrl
a) should be declared in the dialog class as CRichEditCtrl pCRichEditCtrl;
b) should be connected to the ID of the control (e.g.: IDC_RICHEDIT21), like
void CTextFormatterDlg::DoDataExchange(CDataExchange* pDX)
{ CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_RICHEDIT21, pCRichEditCtrl);
}
c) I have tested the following code and it works for me (adds "aa" to the control window on each button click)
pCRichEditCtrl.SetSel(pCRichEditCtrl.GetTextLength(), -1);
pCRichEditCtrl.ReplaceSel(TEXT("aa"));

I share the final solution with the community to be available for those who faces with the same issue. I don't know why do I have to use Update(FALSE); on the CWinApp inheritance two times but it solves everything. If someone has an idea or a better (nicer) solution don't hesitate to share it with us, I'll move the accepted flag to that version (if it is possible, I haven't tried it before).
void CTextFormatterDlg::OnBnClickedButton1()
{
StreamReader^ objReader = gcnew StreamReader("c:\\text.txt");
String ^sLine = objReader->ReadLine();
UpdateData(FALSE); //this is the first unexpected first aid
while (sLine != nullptr)
{
pCRichEditCtrl.SetSel(pCRichEditCtrl.GetTextLength(), -1);
pCRichEditCtrl.ReplaceSel(CString(sLine + "\r\n"));
UpdateData(FALSE); //this is the second unexpected first aid
sLine = objReader->ReadLine();
}
objReader->Close();
}

Related

MFC MDI CtabView hidden / remove navigation controls that are not used

I have 4 buttons that have no direct application to my program. I would like to hide or remove them. I've searched to find out what they are called...they look like navigation, left/right arrows, next/previous. I can't seem to find what they are called. I have looked on the Microsoft site and looking at the CTabView members doesn't seem to jump out and say "hey, these are what you're looking for"....
I'm hoping it is a relatively easy task. Anyone know how to just "turn them off"?
Thanks.
UPDATE:
I was able to resolve the C4430 mentioned by moving the new function before the existing in OutputWnd.h and that solved the issue in the output pane area where the arrows are now gone. What I forgot to mention is that I have another mechanism AddView that is creating 2 runtime classes and putting those into a tabbed document view. This time, I've been using GetTabControl() to make it pretty, but this also suffers from the same issue, the scroll arrows are now present.
This is what the code looks like that creates the 2 new tabs:
Above this code is the constructor/destructor/headers, nothing else.
IMPLEMENT_DYNCREATE(CTrackView, CTabView)
void CTrackView::OnInitialUpdate()
{
// add document views
AddView(RUNTIME_CLASS(CTrainView), AfxStringID(IDS_TRAIN));
AddView(RUNTIME_CLASS(CStationView), AfxStringID(IDS_STATION));
GetTabControl().EnableTabSwap(TRUE);
GetTabControl().SetLocation(CMFCBaseTabCtrl::Location::LOCATION_BOTTOM);
GetTabControl().ModifyTabStyle(CMFCTabCtrl::STYLE_3D);
GetTabControl().SetActiveTabBoldFont(TRUE);
CTabView::OnInitialUpdate();
}
I have tried to comment out CTabView::OnInitialUpdate(); but I know it won't and didn't affect the arrows. I done some searching on the control and I don't see any examples to remove the arrows, I assume another override is in order. I will follow the method shown in the other example, I am looking to see if it can be fixed similar to what has been shown.
Do these share the same CMFCTabCtrl mechanism or is this something different?
Update 2:
The OutputWnd.cpp that the MFC wizard creates has the same issue now that I've modified the tab control, I can't find the right pointer to fix the issue where &tabCtrl()is an unknown identifier. EDIT: This was the issue, I found the fix, see update 3 to see the resolution.
int COutputWnd::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CDockablePane::OnCreate(lpCreateStruct) == -1)
return -1;
CRect rectDummy;
rectDummy.SetRectEmpty();
// Create User Define tab style:
int UserTabStyle = AfxGetApp()->GetProfileInt(_T("Settings"), _T("UserTabStyle"), 0); //Get value from registry
// If the key doesn't exist, UserTableStyle will be 0 or FALSE;
if (UserTabStyle != FALSE && UserTabStyle <= 8) { // User selected tab style type
int EnumUserTabStyle = UserTabStyle - 1; // Fix enum if key doesn't exist.
if (!m_wndTabs.Create(static_cast<CMFCTabCtrl::Style>(EnumUserTabStyle), rectDummy, this, 1))
{
TRACE0("Failed to create output tab window\n");
return -1; // fail to create
}
}
else { // Default tabs style if Reg key does not exist i.e. new install/program reset
if (!m_wndTabs.Create(CMFCTabCtrl::STYLE_FLAT, rectDummy, this, 1))
{
TRACE0("Failed to create output tab window\n");
return -1; // fail to create
}
}
// Nicely hack to access protected member
class CMFCTabCtrlEx : public CMFCTabCtrl
{
public:
void SetDisableScroll() { m_bScroll = FALSE; }
};
// One-Liner to Disable navigation control
((CMFCTabCtrlEx*)&tabCtrl())->SetDisableScroll();
// Create output panes:
const DWORD dwStyle = LBS_NOINTEGRALHEIGHT | WS_CHILD | WS_VISIBLE | WS_HSCROLL | WS_VSCROLL | WS_BORDER;
if (!m_wndOutputBuild.Create(dwStyle, rectDummy, &m_wndTabs, 2) ||
!m_wndOutputDebug.Create(dwStyle, rectDummy, &m_wndTabs, 3))
{
TRACE0("Failed to create output windows\n");
return -1; // fail to create
}
UpdateFonts();
CString strTabName;
BOOL bNameValid;
//Attach list windows to tab:
bNameValid = strTabName.LoadString(IDS_STATUS_TAB);
ASSERT(bNameValid);
m_wndTabs.AddTab(&m_wndOutputBuild, strTabName, (UINT)0);
bNameValid = strTabName.LoadString(IDS_DEBUG_TAB);
ASSERT(bNameValid);
m_wndTabs.AddTab(&m_wndOutputDebug, strTabName, (UINT)1);
int EnableDebugTab = AfxGetApp()->GetProfileInt(_T("Settings"), _T("EnableDebugTab"), 0); //Get value from registry
if (EnableDebugTab == FALSE)
{
OnOutputtabsDebug(); //Check to see if it should be enabled
}
return 0;
}
Update 3:
I found the answer to my unknown identifier, I was trying to call a function that didn't exist. Reformed as such and it works as expected:
// Nicely hack to access protected member
class CMFCTabCtrlEx : public CMFCTabCtrl
{
public:
void SetDisableScroll() { m_bScroll = FALSE; }
};
// One-Liner to Disable navigation control
((CMFCTabCtrlEx*)&m_wndTabs)->SetDisableScroll();
There is no public, documented API to hide those navigation buttons. However, digging into the MFC sources finds that:
the arrows are CMFCTabButton m_btnScrollLeft, m_btnScrollRight, m_btnScrollFirst, m_btnScrollLast; in CMFCTabCtrl;
they are created in CMFCTabCtrl::OnCreate whenever CMFCTabCtrl::m_bScroll is TRUE;
CMFCTabCtrl::m_bScroll is set to TRUE in CMFCTabCtrl::Create if any of the styles STYLE_FLAT, STYLE_FLAT_SHARED_HORZ_SCROLL, STYLE_3D_SCROLLED, STYLE_3D_ONENOTE, STYLE_3D_VS2005, or STYLE_3D_ROUNDED_SCROLL is used.
With that insight, the navigation buttons can be turned off in a couple of ways.
By the book: create the CMFCTabCtrl without any of the styles that enable those buttons, which leaves only STYLE_3D available. That loses the navigation buttons, indeed, but the styling of the tab control also becomes different, and the tabs themselves display as small rectangles rather than trapezoids.
Undocumented: override the CMFCTabCtrl::m_bScroll and set it to FALSE before the tab window gets created. For example, derive a class CMyTabCtrl to clear m_bScroll.
class CMyTabCtrl : public CMFCTabCtrl
{
protected:
BOOL PreCreateWindow(CREATESTRUCT &cs) override
{
m_bScroll = FALSE;
return CMFCTabCtrl::PreCreateWindow(cs);
}
};
Then instantiate the control as CMyTabCtrl m_wndTabs; instead of CMFCTabCtrl m_wndTabs;.
I remembered I solved this in the past with an One-liner.
Here a solution (hack) to direct access the m_bScroll Variable in your CTrackView::::OnCreate() function. OnInitialUpdate() comes too late as dxiv explained.
int void CTrackView::::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CTabView::OnCreate(lpCreateStruct) == -1)
return -1;
// add document views
AddView(RUNTIME_CLASS(CTrainView), AfxStringID(IDS_TRAIN));
AddView(RUNTIME_CLASS(CStationView), AfxStringID(IDS_STATION));
:
:
// Nicely hack to access protected member
class CMFCTabCtrlEx : public CMFCTabCtrl
{
public:
void SetDisableScroll() { m_bScroll = FALSE; }
};
// One-Liner to Disable navigation control
((CMFCTabCtrlEx*)&GetTabControl())->SetDisableScroll();
}

Load icon from .DLL in wxWidgets

I am attempting to load a wxIcon in Windows by loading from a system DLL (as the mime system told me that the icon for such a file type was in the DLL), eg.
wxIcon icon;
icon.LoadFile("C:\\WINDOWS\\system32\\zipfldr.dll", wxICON_DEFAULT_TYPE);
This fails but I was wondering if there was any way in the codebase of loading this, other than resorting to native Win32 functions.
Also, if there are native Win32 functions, does anyone know what they are?
EDIT: I have tried the following with no success:
::wxInitAllImageHandlers();
wxMimeTypesManager manager;
wxFileType* type = manager.GetFileTypeFromExtension("sys");
wxIconLocation location;
if (type->GetIcon(&location))
{
// location is something like C:\WINDOWS\system32\imageres.dll
wxIcon icon;
if (!icon.LoadFile(location.GetFileName(), wxBITMAP_TYPE_ICON /*I have tried wxICON_DEFAULT_TYPE too*/))
{
// Failed!
}
}
EDIT 2: In response to VZ, I have tried the following with no success sadly:
::wxInitAllImageHandlers();
wxMimeTypesManager manager;
wxFileType* type = manager.GetFileTypeFromExtension("sys");
wxIconLocation location;
if (type->GetIcon(&location))
{
// location is something like C:\WINDOWS\system32\imageres.dll,
//with an appropriate index as retrieved by location.GetIndex(), which is -67.
wxIcon icon(location);
if (!icon.IsOk())
{
BREAK;
// Failed!
}
}
EDIT 3:
Thanks for everyone's help - works fine if I use wxBITMAP_TYPE_ICO instead of wxBITMAP_TYPE_ICON (notice the N), and also I was putting my test code in my app's constructor instead of in ::OnInit. It worked in OnInit but not in the constructor so that's a lesson learned!
Thanks everyone for the help and speedy responses, much appreciated as always.
It should work if you specify type wxBITMAP_TYPE_ICO.
The first argument to LoadFile() must specify the icon resource ID when using wxBITMAP_TYPE_ICO (which is indeed what you need to use when loading icons from files, and not resources of the current module), i.e. you're also missing the ;N part at the end, where N is the value returned by wxFileTypeInfo::GetIconIndex().
But to avoid dealing with this explicitly, you should just use wxFileType::GetIcon() and construct wxIcon from the wxIconLocation filled in by it.
For example, this:
diff --git a/samples/minimal/minimal.cpp b/samples/minimal/minimal.cpp
index 0d91f7fc75..3623aacc56 100644
--- a/samples/minimal/minimal.cpp
+++ b/samples/minimal/minimal.cpp
## -123,6 +123,12 ## bool MyApp::OnInit()
if ( !wxApp::OnInit() )
return false;
+ wxIcon icon(wxIconLocation(R"(c:\Windows\system32\imageres.dll)", -67));
+ if ( icon.IsOk() )
+ {
+ wxLogMessage("Loaded icon of size %d*%d", icon.GetWidth(), icon.GetHeight());
+ }
+
// create the main application window
MyFrame *frame = new MyFrame("Minimal wxWidgets App");
shows the expected message about loading the icon of size 32 by 32.

GetOwner() cause unreal editor crash

I'm new in using c++ and UE.
I tried some simple programming but the editor crash.
#include "NewActorComponent.h"
#include "Runtime/Engine/Classes/GameFramework/Actor.h"
UNewActorComponent::UNewActorComponent()
{
PrimaryComponentTick.bCanEverTick = true;
GetOwner()->GetName();
}
I knew maybe the output is null so it is crashed,but idk how to expect the error without any crash.
It's possible the actor component is created but not initialized or attached to an object. You should gate these kind of checks behind IF statements, or use the assert/check macros.
Also, you may want to use the BeginPlay() function instead of the constructor. BeginPlay requires the component to be registered and initialized so it should have an owner.
GetName();
To find the owner of the component.
Ex: When inserting a component in the chair, a reference to the chair will be returned.
From Unreal Engine API Reference:
UObjectBaseUtility::GetName
Syntax: FString GetName()
Remarks
Returns the name of this object (with no path information)
OK, Follow this steps:
1) File -> New Project -> C++ -> Basic Code -> With Starter Content
2) Inside MinimalDefault Map select one chair and pick Add Component Button.
3) Choose New C++ Component
4) Choose Actor Component Class and click em Next Button
5) In Visual Studio inside NewActorComponent.cpp insert code below in BeginPlay() function
UNewActorComponent::UNewActorComponent()
{
PrimaryComponentTick.bCanEverTick = true;
FString ObjectName = GetOwner()->GetName();
UE_LOG(LogTemp, Warning, TEXT("ObjetctName: %s"), *Objectname);
}
6) Show Log Window in Unreal Engine 4
Log Windows
7) Compile!
8) See Results in Log Window
logwindowresults
Below Complete Code. It Works! Enjoy!
#include "NewActorComponent.h"
#include "Runtime/Engine/Classes/GameFramework/Actor.h"
UNewActorComponent::UNewActorComponent()
{
PrimaryComponentTick.bCanEverTick = true;
}
void UNewActorComponent::BeginPlay()
{
Super::BeginPlay();
FString NameOfObject = GetOwner()->GetName();
UE_LOG(LogTemp, Warning, TEXT("Name is: %s"), *NameOfObject)
}
void UNewActorComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
}

How to make MFC Ribbon Statusbar act like the regular CStatusBar

The first image shows what I want to do. The second one shows what I get.
I want the status bar to show the state of the special keys CAPS LOCK, NUM LOCK and SCROLL LOCK. This image is from an old project using the CStatusBar.
This snapshot is from CMainFrame class.
This image shows how I am doing it in Visual C++ 2015 MFC and the results I get. This snapshot is from CMainFrame class, too.
My question is : Can anyone tell me how my application can intercept the change from toggle buttons CAPS LOCK and NUM LOCK then update the user interface.
I tried to use this code but it doesn't work :
ON_UPDATE_COMMAND_UI(ID_INDICATOR_STYLE, &CMainFrame::OnUpdateStyle)
ON_UPDATE_COMMAND_UI(ID_INDICATOR_FOLD, &CMainFrame::OnUpdateFold)
ON_UPDATE_COMMAND_UI(ID_INDICATOR_OVR, &CMainFrame::OnUpdateInsert)
Thanks in advance.
First of all the standard behavior of CStatusBar is not supported by CMFCRibbonStatusBar.
The good news is that it is very easy to implement the same behavior.
Here is what you have to do in order to implement it in your application:
Add this to message map of your main frame class or child frame in case of MDI:
ON_UPDATE_COMMAND_UI(ID_INDICATOR_CAPS, &CMainFrame::OnUpdateButtonsState)
ON_UPDATE_COMMAND_UI(ID_INDICATOR_NUM, &CMainFrame::OnUpdateButtonsState)
ON_UPDATE_COMMAND_UI(ID_INDICATOR_SCRL, &CMainFrame::OnUpdateButtonsState)
The actual update handler should look like this:
void CMainFrame::OnUpdateButtonsState(CCmdUI* pCmdUI)
{
UINT nVK;
UINT flag = 0x0001;
switch (pCmdUI->m_nID)
{
case ID_INDICATOR_CAPS:
nVK = VK_CAPITAL;
break;
case ID_INDICATOR_NUM:
nVK = VK_NUMLOCK;
break;
case ID_INDICATOR_SCRL:
nVK = VK_SCROLL;
break;
case ID_INDICATOR_KANA:
nVK = VK_KANA;
break;
default:
TRACE(traceAppMsg, 0, "Warning: OnUpdateKeyIndicator - unknown indicator 0x%04X.\n",
pCmdUI->m_nID);
pCmdUI->ContinueRouting();
return; // not for us
}
pCmdUI->SetCheck(::GetKeyState(nVK) & flag);
}
I solved it by moving the code to CChildFrame class.
ON_UPDATE_COMMAND_UI(ID_INDICATOR_CAPS, &CChildFrame::OnUpdateIndicators)
ON_UPDATE_COMMAND_UI(ID_INDICATOR_NUM, &CChildFrame::OnUpdateIndicators)
ON_UPDATE_COMMAND_UI(ID_INDICATOR_SCRL, &CChildFrame::OnUpdateIndicators)
And then
void CChildFrame::OnUpdateIndicators(CCmdUI *pCmdUI)
{
pCmdUI->Enable();
// ... the rest of the above code
CString text;
if (::GetKeyState(nVK) & flag)
text.LoadStringW(pCmdUI->m_nID);
pCmdUI->SetText(text);
}

Windows phone 8 on emulator - why can't I play audio files?

I'm converting an app that was written in Silverlight, and so far I've succeeded in solving all of the problems, except for one:
For some reason, the emulator refuses to play any audio files of the app, and it doesn't even throw an exception. I've checked, and in the ringtone category it can make sounds.
The original code was :
<Grid x:Name="sharedFullScreenFilePathContainer"
Tag="{Binding StringFormat=\{0\},Converter={StaticResource fullScreenImageConverter}}">
<Image x:Name="fullScreenImage" Stretch="Fill"
Source="{Binding ElementName=sharedFullScreenFilePathContainer,Path=Tag, StringFormat=../Assets/images/\{0\}.jpg}"
ImageFailed="onFullScreenImageFailedToLoad" MouseLeftButtonDown="onPressedOnFullScreenImage" />
<MediaElement x:Name="mediaPlayer" AutoPlay="True"
Source="{Binding ElementName=sharedFullScreenFilePathContainer,Path=Tag, StringFormat=../Assets/sounds/\{0\}.wma}" />
</Grid>
so, the image that I set to this item's context is really shown, but the sound that really exists on the path I set to it doesn't play (I've checked in the "Bin" folder).
I've tried to use code instead of xaml, but I still have the same problem.
I've tried this (though it's usually used for background music):
AudioTrack audioTrack = new AudioTrack(new Uri("../Assets/sounds/" + fileToOpen, UriKind.Relative), "", "", "", null);
BackgroundAudioPlayer player = BackgroundAudioPlayer.Instance;
player.Track = audioTrack;
player.Play();
It didn't play anything, and also didn't throw any exception.
I've also tried the next code, but it throws an exception (file not found exception) probably because I don't call it right:
Stream stream = TitleContainer.OpenStream("#Assets/sounds/" + fileToOpen);
SoundEffect effect = SoundEffect.FromStream(stream);
FrameworkDispatcher.Update();
effect.Play();
I've also tried using wma files but it also didn't work.
I also tried to play with the "copy to output directory" parameter of the mp3 files (to "always" and "only if new" ) and with the "build action" parameter (to "none" and "content" ). Nothing helps.
Can anyone please help me? I didn't develop for Silverlight/WP for a very long time and I can't find out how to fix it .
Btw, since later I need to know when the sound has finished playing (and also to be able to stop it), I would like to use code anyway. I would be happy if you could also tell me how to do it too (I can ask it on a new post if needed).
EDIT:
ok , i've found out the problem : i kept getting a weird exception when using the MediaPlayer.Play() method , and after checking out about the exception , i've found out that it's a known issue , and that i need to call FrameworkDispatcher.Update(); right before i call the Play() method .
so the solution would be to do something like this:
Song song = Song.FromUri(...);
MediaPlayer.Stop();
FrameworkDispatcher.Update();
MediaPlayer.Play(song);
the exception is:
'System.InvalidOperationException' occurred in System.Windows.ni.dll"
i've found the solution here .
Now the question is why , and how come I didn't find anything related to it in the demos of windows phone ? Also , i would like to know what this function does .
ok , since nobody gave me an answer to both questions , and I still wish to give the bounty , I will ask another question :
If there is really no solution other than using the MediaPlayer class for windows phone , how do i capture the event of finishing playing an audio file ? Even getting the audio file duration doesn't work (keeps returning 0 length , no matter which class i've tried to use) ...
The BackgroundAudioPlayer can play files only from isolated storage or from a remote URI, that is why you can here anything!
If you have your file as resources in your app, you must first copy them to the isolated store, and then make a reference to the file in the isolated store to your BackgroundAudioPlayer.
private void CopyToIsolatedStorage()
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
string[] files = new string[]
{ "Kalimba.mp3",
"Maid with the Flaxen Hair.mp3",
"Sleep Away.mp3" };
foreach (var _fileName in files)
{
if (!storage.FileExists(_fileName))
{
string _filePath = "Audio/" + _fileName;
StreamResourceInfo resource = Application.GetResourceStream(new Uri(_filePath, UriKind.Relative));
using (IsolatedStorageFileStream file = storage.CreateFile(_fileName))
{
int chunkSize = 4096;
byte[] bytes = new byte[chunkSize];
int byteCount;
while ((byteCount = resource.Stream.Read(bytes, 0, chunkSize)) > 0)
{
file.Write(bytes, 0, byteCount);
}
}
}
}
}
}
And then you can make a list of your songs
private static List<AudioTrack> _playList = new List<AudioTrack>
{
new AudioTrack(new Uri("Kalimba.mp3", UriKind.Relative),
"Kalimba",
"Mr. Scruff",
"Ninja Tuna",
null),
new AudioTrack(new Uri("Maid with the Flaxen Hair.mp3", UriKind.Relative),
"Maid with the Flaxen Hair",
"Richard Stoltzman",
"Fine Music, Vol. 1",
null),
new AudioTrack(new Uri("Sleep Away.mp3", UriKind.Relative),
"Sleep Away",
"Bob Acri",
"Bob Acri",
null),
// A remote URI
new AudioTrack(new Uri("http://traffic.libsyn.com/wpradio/WPRadio_29.mp3", UriKind.Absolute),
"Episode 29",
"Windows Phone Radio",
"Windows Phone Radio Podcast",
null)
};
And play your tracks!
private void PlayNextTrack(BackgroundAudioPlayer player)
{
if (++currentTrackNumber >= _playList.Count)
{
currentTrackNumber = 0;
}
PlayTrack(player);
}
private void PlayPreviousTrack(BackgroundAudioPlayer player)
{
if (--currentTrackNumber < 0)
{
currentTrackNumber = _playList.Count - 1;
}
PlayTrack(player);
}
private void PlayTrack(BackgroundAudioPlayer player)
{
// Sets the track to play. When the TrackReady state is received,
// playback begins from the OnPlayStateChanged handler.
player.Track = _playList[currentTrackNumber];
}
If you want the MediaElement to work from your code you can do something like this!
MediaElement me = new MediaElement();
// Must add the MediaElement to some UI container on
// your page or some UI-control, otherwise it will not play!
this.LayoutRoot.Children.Add(me);
me.Source = new Uri("Assets/AwesomeMusic.mp3", UriKind.RelativeOrAbsolute);
me.Play();
Use the MediaElement instead, this can play media files stored in your application, but stops playing when the application stops (you can make some advance chance to your app so it keep running, but it will not work very well)
In your XAML:
<Button x:Name="PlayFile"
Click="PlayFile_Click_1"
Content="Play mp3" />
In your Code behind:
MediaElement MyMedia = new MediaElement();
// Constructor
public MainPage()
{
InitializeComponent();
this.LayoutRoot.Children.Add(MyMedia);
MyMedia.CurrentStateChanged += MyMedia_CurrentStateChanged;
MyMedia.MediaEnded += MyMedia_MediaEnded;
}
void MyMedia_MediaEnded(object sender, RoutedEventArgs e)
{
System.Diagnostics.Debug.WriteLine("Ended event " + MyMedia.CurrentState.ToString());
// Set the source to null, force a Close event in current state
MyMedia.Source = null;
}
void MyMedia_CurrentStateChanged(object sender, RoutedEventArgs e)
{
switch (MyMedia.CurrentState)
{
case System.Windows.Media.MediaElementState.AcquiringLicense:
break;
case System.Windows.Media.MediaElementState.Buffering:
break;
case System.Windows.Media.MediaElementState.Closed:
break;
case System.Windows.Media.MediaElementState.Individualizing:
break;
case System.Windows.Media.MediaElementState.Opening:
break;
case System.Windows.Media.MediaElementState.Paused:
break;
case System.Windows.Media.MediaElementState.Playing:
break;
case System.Windows.Media.MediaElementState.Stopped:
break;
default:
break;
}
System.Diagnostics.Debug.WriteLine("CurrentState event " + MyMedia.CurrentState.ToString());
}
private void PlayFile_Click_1(object sender, RoutedEventArgs e)
{
// Play Awesome music file, stored as content in the Assets folder in your app
MyMedia.Source = new Uri("Assets/AwesomeMusic.mp3", UriKind.RelativeOrAbsolute);
MyMedia.Play();
}
Audio track plays audio files stored in isolated storage or streamed over the internet.
Playing audio files stored within the application package works fine for me. I got files named like "Alarm01.wma" in project folder Resources\Alarms. I then play these sounds like this:
using Microsoft.Xna.Framework.Media;
...
Song s = Song.FromUri("alarm", new Uri(#"Resources/Alarms/Alarm01.wma", UriKind.Relative));
MediaPlayer.Play(s);
Also don't forget to reference Microsoft.Xna.Framework library.
I guess it should work fine for mp3 files and files stored in IsolatedStorage as well.