Xamarin.Forms中的计时器 [英] Timer in Xamarin.Forms

查看:895
本文介绍了Xamarin.Forms中的计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构建自己的音频播放器(因为没有可用的插件).我已经使用滑块来显示播放器的进度.我可以允许用户在移动滑块时转到特定的位置,但无法与正在播放的录音同步.

I want to build my own audio player (as there no plugins available). I have used a slider to show progress of the player. I could allow user to go to specific location when the slider is moved but I can not synchronize it with the recording being played.

表格

int i = 1;
Button btnPlay = new Button
{
    Text = "Play/Pause",
    Command = new Command(() =>
    {
        DependencyService.Get<IAudio>().PlayMp3File();
        TimeSpan tmspan = new TimeSpan(00, 00, 00);
        label.Text = String.Format("{0:hh\\:mm\\:ss}", tmspan.Add(TimeSpan.FromMilliseconds(i)));
        i++;
        return true;
    })
};
Button btnStop = new Button { Text = "Stop" };
TimeSpan timeSpan = DependencyService.Get<IAudio>().GetInfo();
Label lblDuration = new Label { Text = String.Format("{0:hh\\:mm\\:ss}", timeSpan) };

var slider = new Slider {
    Minimum = 0,
    Maximum = timeSpan.TotalHours,
};
var label = new Label {
    Text = "Slider value is 0",
    FontSize = 25,
    HorizontalOptions = LayoutOptions.Start,
};
slider.ValueChanged += 
    (sender, e) => 
    {
        label.Text = String.Format("Slider value is {0:hh\\:mm\\:ss}", TimeSpan.FromMilliseconds(e.NewValue));
        DependencyService.Get<IAudio>().SeekTo(Convert.ToInt32(e.NewValue));
    };
MainPage = new ContentPage
{
    Content = new StackLayout 
    {
        Children = 
        {
            btnPlay,
            btnStop,
            slider,
            lblDuration,
            label
        }
    },  
    Padding = new Thickness (10, Device.OnPlatform (20, 0, 0), 10, 5)
};

服务

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using AudioTest.Droid;
using Xamarin.Forms;
using Android.Media;
using System.Threading.Tasks;

[assembly: Dependency(typeof(AudioService))]

namespace AudioTest.Droid
{
    public class AudioService : IAudio
    {
        public AudioService() { }

        MediaPlayer player = null;

        public async Task StartPlayerAsync()
        {
            try
            {
                if (player == null)
                {
                    player = new MediaPlayer();
                    player = MediaPlayer.Create(global::Android.App.Application.Context, Resource.Raw.test);
                    player.Start();
                }
                else
                {
                    if (player.IsPlaying == true)
                    {
                        player.Pause();
                    }
                    else
                    {
                        player.Start();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.StackTrace);
            }
        }

        public void StopPlayer()
        {
            if ((player != null))
            {
                if (player.IsPlaying)
                {
                    player.Stop();
                }
                player.Release();
                player = null;
            }
        }

        public async Task PlayMp3File()
        {
            await StartPlayerAsync();
        }

        public void Stop()
        {
            this.StopPlayer();
        }

        public async Task SeekTo( int s)
        {
            await seekTo(s);
        }

        public double CurrentPosition()
        {
            if ((player != null))
            {
                return player.CurrentPosition;
            }
            else
            { return 0; }
        }

        private async Task seekTo(int mseconds)
        {
            if (player == null)
            {
                player = new MediaPlayer();
                player = MediaPlayer.Create(global::Android.App.Application.Context, Resource.Raw.test);

            }

            player.SeekTo(mseconds);
            player.Start();
        }



        public TimeSpan GetInfo()
        {
            int arr;
            if (player == null)
            {
                player = new MediaPlayer();
                player = MediaPlayer.Create(global::Android.App.Application.Context, Resource.Raw.test);

            }
            arr = player.Duration;

            return TimeSpan.FromMilliseconds(arr);//TimeSpan.FromMilliseconds(arr).TotalMinutes;
        }
    }
}

任何人都知道如何去做吗?

Anyone has any idea on how to go about it?

编辑 屏幕截图

在播放时,计时器应启动,并且我的滑块值也应增加.暂停时,计时器和滑块应暂停,停止时应停止.

On play the timer should start and also my slider value should increment. On pause the timer and slider should be paused and on stop it should be stopped.

推荐答案

看看

Take a look at Device class in Xamarin.Forms and particularly at StartTimer method.

鉴于此,您可以设置计时器:

Given that, you can setup your timer :

Device.StartTimer(TimeSpan.FromMilliseconds(300.0), TimerElapsed);

private bool TimerElapsed()
{
    Device.BeginInvokeOnMainThread(() => 
    {
        //put here your code which updates the view
    });
    //return true to keep timer reccurring
    //return false to stop timer
}

它将大约每300毫秒触发一次(取决于设备的功能)

It will fire approximately every 300 milliseconds (depending on the device capabilities)

关于您的代码,您可以从类似这样的内容开始:

Regarding your code, you can start with something like that:

1.在播放命令中添加以下内容:

1.Add following to your play command :

Device.StartTimer(TimeSpan.FromSeconds(1.0), CheckPositionAndUpdateSlider);

2.添加CheckPositionAndUpdateSlider方法:

private bool CheckPositionAndUpdateSlider()
{
    var position = DependencyService.Get<IAudio>().GetCurrentPosition();
    Device.BeginInvokeOnMainThread(() => 
    {
         slider.Value = position;
    });
    return true;
}

这篇关于Xamarin.Forms中的计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆