Xamarin.forms中的计时器

时间:2016-05-13 07:05:57

标签: c# xamarin.forms

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

形式

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;
        }
    }
}

任何人都知道如何去做?

修改的 屏幕截图 enter image description here

在播放时,计时器应该开始,我的滑块值也应该增加。暂停时,应暂停计时器和滑块,停止时应停止计时器和滑块。

1 个答案:

答案 0 :(得分:2)

查看public static boolean getData(String ids){ String idAry[] = ids.split(","); ArrayList<String> idStr = new ArrayList<String>(); for (String id:idAry){ idStr.add('"'+id+'"'); } String abc = idStr.toString().replace("[", "").replace("]", ""); System.out.println(abc); MultiGetResponse multiGetItemResponses = client.prepareMultiGet() .add("loc", "message", abc).get(); // MultiGetResponse multiGetItemResponses = client.prepareMultiGet() // .add("loc", "message", "AVSoemK55hnvwxeDfgCc", "AVSoemK55hnvwxeDfgCa").get(); // for(MultiGetItemResponse itemResponse: multiGetItemResponses){ GetResponse response2 = itemResponse.getResponse(); if(response2.isExists()){ String json2 = response2.getSourceAsString(); System.out.println(json2); } } return true; } 中的{{3}}课程,尤其是Xamarin.Forms方法。

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

StartTimer

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

关于您的代码,您可以从以下内容开始:

1.添加以下播放命令:

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
}

2.添加Device.StartTimer(TimeSpan.FromSeconds(1.0), CheckPositionAndUpdateSlider); 方法:

CheckPositionAndUpdateSlider