I'm novice in programming and this is my first project ever in c# xamarin. I want to set loop on that MediaPlayer but SetLooping method is missing in Android.Media.
I'm using Visual Studio 2017 Community. Here is my code.
Thanks in advance for any feedback :D
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Media;
using Android.Content;
using Android.Preferences;
using Android.Views.Animations;
namespace App2
{
[Activity(Label = "FirstApp 1.34", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
MediaPlayer music;
protected override void OnPause()
{
base.OnPause();
music.Pause();
}
protected override void OnDestroy()
{
music.Release();
base.OnDestroy();
}
protected override void OnResume()
{
music.Start();
base.OnResume();
}
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
music = MediaPlayer.Create(this, Resource.Raw.bgsound);
music.SetVolume(0.7f, 0.7f);
music.Start();
}
SetLooping method is mapped as a property in Xamarin.Android and you should use the Looping property instead. Take a look at: Android.Media.MediaPlayer.Looping Property
Try this on your code
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
music = MediaPlayer.Create(this, Resource.Raw.bgsound);
music.SetVolume(0.7f, 0.7f);
music.Start();
music.Looping = true;
}
Related
I'm Xamarin Developer
I want to play *.mp3 or *.wav file in the localized application
so I divided the file like that
and I implement code in dependency service like
public void OnePlaySound()
{
_mediaPlayer = MediaPlayer.Create(context, Resource.Raw.wavone);
_mediaPlayer.Start();
_mediaPlayer.Completion += delegate
{
if (_mediaPlayer != null)
{
_mediaPlayer.Stop();
_mediaPlayer.Release();
_mediaPlayer = null;
}
};
}
but _mediaPlayer always returns null..
is there any solution to use the localizing raw files?
I understand from your description that you want to use MediaPlayer to play an audio file in the Resource/Raw folder using dependencyservice in Xamarin.Forms. Here is an example:
First, create interface named IPlayAudio in .Net standard library project(shared code).
public interface IPlayAudio
{
void playaudio();
}
Then create one class that implements IPlayAudio in the Android platform, the platform implementations must be registered with the DependencyService, so that Xamarin.Forms can locate them at runtime.
[assembly: Dependency(typeof(PlayAudiomethod))]
namespace playvideo.Droid
{
public class PlayAudiomethod : IPlayAudio
{
private MediaPlayer _player;
public void playaudio()
{
_player = MediaPlayer.Create(MainActivity.mac, Resource.Raw.MyAudio);
_player.Start();
}
}
}
For MainActivity.mac, please create static member called "mac" in MainActivity and set it after the call to LoadApplication.
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
public static MainActivity mac;
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
mac = this;
}
}
Now you can play audio from the Xamarin.Forms shared code.
private void mediaplayer_Clicked(object sender, EventArgs e)
{
DependencyService.Get<IPlayAudio>().playaudio();
}
Note: please set xxx.mp3 Build Action as AndroidResource.
I want to play a mp4 video which I have put in the folder Resources/raw. The following is my code and the error "A field initialiser can not be applied to the non static fiel or non static method or property" (translated from German) is displayed, 'FindViewById(Resource.Id.vv)' being the underlined part. In my layout file I have included a VideoView with the id 'vd'. I would be very thankful for every help to play my video!
using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Runtime;
using Android.Widget;
namespace App_1_design
{
[Activity(Theme = "#style/AppTheme", MainLauncher = true]
public class MainActivity : AppCompatActivity
{
VideoView vid = (VideoView) FindViewById(Resource.Id.vv);
We need to initialize controls in the OnCreate event after setting the layout file like:
[Activity(Label = "#string/app_name", Theme = "#style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
VideoView vid;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
vid = FindViewById<VideoView>(Resource.Id.vv);
var uri = Android.Net.Uri.Parse("android.resource://" + PackageName + "/" + Resource.Raw.sample_video);
vid.SetVideoURI(uri);
vid.Start();
}
}
Update
why now the error message says 'resource does not contain a definition
for raw'?
Make sure the build action of your video is AndroidResource. And then we could access this resource through Resource.Raw.[yourVideoID].
ConnectivityManager connMgr = (ConnectivityManager)this.Activity.GetSystemService(Android.Content.Context.ConnectivityService);
NetworkInfo networkInfo = connMgr.ActiveNetworkInfo;
bool isConnected = networkInfo.IsConnected;
this code is in the onCreateView method in my fragment and when i run the app i get the error:
Unhandled Exception:
System.NullReferenceException: Object reference not set to an instance of an object. occurred
it would be great if someone would explain to me what "not set to an instance of an object means" as i dont quite understand. still a little new to xamarin and c# in general.
heres the fragament1.cs file:
using Android.OS;
using Android.Support.V4.App;
using Android.Views;
using Android.Webkit;
namespace TabsApp.Fragments
{
public class Fragment1 : Fragment
{
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your fragment here
}
public static Fragment1 NewInstance()
{
var frag1 = new Fragment1 { Arguments = new Bundle() };
return frag1;
}
WebView webView;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var ignored = base.OnCreateView(inflater, container, savedInstanceState);
View v = inflater.Inflate(Resource.Layout.fragment1, container, false);
webView = v.FindViewById<WebView>(Resource.Id.webView);
webView.LoadUrl("https://google.com");
webView.Settings.JavaScriptEnabled = true;
webView.SetWebViewClient(new WebViewClient());
return v;
}
public void OnBackPressed()
{
webView.GoBack();
}
}
}
and heres the MainActivity.cs file:
using Android.App;
using Android.OS;
using TabsApp.Fragments;
using Android.Content.PM;
using Android.Support.Design.Widget;
using Android.Support.V7.App;
namespace TabsApp
{
[Activity(Label = "#string/app_name", MainLauncher = true, LaunchMode = Android.Content.PM.LaunchMode.SingleTop, Icon = "#drawable/icon",
ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, ScreenOrientation = ScreenOrientation.Portrait)]
public class MainActivity : AppCompatActivity
{
BottomNavigationView bottomNavigation;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.main);
var toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
if (toolbar != null)
{
SetSupportActionBar(toolbar);
SupportActionBar.SetDisplayHomeAsUpEnabled(false);
SupportActionBar.SetHomeButtonEnabled(false);
}
bottomNavigation = FindViewById<BottomNavigationView>(Resource.Id.bottom_navigation);
bottomNavigation.NavigationItemSelected += BottomNavigation_NavigationItemSelected;
LoadFragment(Resource.Id.menu_home);
}
private void BottomNavigation_NavigationItemSelected(object sender, BottomNavigationView.NavigationItemSelectedEventArgs e)
{
LoadFragment(e.Item.ItemId);
}
void LoadFragment(int id)
{
Android.Support.V4.App.Fragment fragment = null;
switch (id)
{
case Resource.Id.menu_home:
fragment = Fragment1.NewInstance();
break;
case Resource.Id.menu_audio:
fragment = Fragment2.NewInstance();
break;
case Resource.Id.menu_video:
fragment = Fragment3.NewInstance();
break;
}
if (fragment == null)
return;
SupportFragmentManager.BeginTransaction()
.Replace(Resource.Id.content_frame, fragment)
.Commit();
}
}
}
Well its pretty simple this looks to me like you do not have your activity context here and for that reason you are unable to get the connMgr
What you need to do is when you call your fragment from your activity pass the current activity to your ~Fragment~ something like this on your fragment call:
Fragment1 newInstance(this);
Receive it in your fragment with something like this in your constructor:
public static AppCompatActivity _activity
public static Fragment1 newInstance(AppCompatActivity activity )
{
_activity =activity ;
//Lines of code }
And in your onCreateView use it like this :
ConnectivityManager connMgr = (ConnectivityManager)_activity.GetSystemService(Android.Content.Context.ConnectivityService);
NetworkInfo networkInfo = connMgr.ActiveNetworkInfo;
bool isConnected = networkInfo.IsConnected;
If it doesn't work lemme know! Goodluck
My Splash Activity just shows a plain white screen. I am in a Xamarin Forms project. When I tried using a style to set the background, it worked, but the image was stretched out, which is why I am trying to use a LinearLayout and ImageView instead. This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace Buddy.Droid
{
[Activity(Label = "HeyBuddy", Icon = "#drawable/icon", Theme = "#style/splashscreen", MainLauncher = true, NoHistory = true)]
public class SplashActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your application here
var imageView = new ImageView(this);
imageView.SetImageResource(Resource.Drawable.splash_screen);
var layout = new LinearLayout(this);
layout.SetBackgroundColor(Color.ParseColor("#0098CC"));
layout.AddView(imageView);
SetContentView(layout);
}
protected override void OnResume()
{
base.OnResume();
StartActivity(typeof(MainActivity));
}
}
}
To programmatically create a Layout with an ImageView:
Create a ViewGroup.LayoutParams with its width and height set to MatchParent
Assign the layoutparams to your ImageView
Assign a ImageView.SetScaleType for how you want to scale your drawable (i.e. ImageView.ScaleType.FitCenter)
Note: You do not need the LinearLayout, just set the background color of your ImageView
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
var layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
var imageView = new ImageView(this)
{
LayoutParameters = layoutParams
};
imageView.SetImageResource(Resource.Drawable.splash_screen);
imageView.SetScaleType(ImageView.ScaleType.FitCenter);
imageView.SetBackgroundColor(Color.ParseColor("#0098CC"));
SetContentView(imageView);
}
protected async override void OnResume()
{
base.OnResume();
await Task.Delay(5000); // simulate some background work....
StartActivity(typeof(MainActivity));
}
I wanna point out that i'm a total newbie in Xamarin.
My goal is to create simple app that after you push the button, it will jump to another layout. My problem is, that after i created a new layout(called layout1) and new activity, I can't reference to this layout in my MainActivity.
freshly created Activity:
namespace Layouts
{
[Activity(Label = "Activity1")]
public class Activity1 : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.layout1);
}
}
}
And my MainActivity:
namespace Layouts
{
[Activity(Label = "Layouts", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView (Resource.Layout.Main);
Button button1 = FindViewById<Button>(Resource.Id.button);
button1.Click += delegate
{
StartActivity(typeof(layout1)); //can't reference layout1 there
};
}
}
}
Any help will be great, thanks :)
StartActivity(typeof(Activity1));