振っている間だけ再生するプレイヤー

#wpdev_jp

振っている間だけ再生するプレイヤー

  1. プロジェクト作成
  2. mp3 ファイルをプロジェクトに追加(参考)し、「出力ディレクトリにコピー」を「新しい場合はコピー」に変更
  3. MediaElement を画面に配置して、Source にmp3のファイル名、AutoPlay はチェックを入れて外す。
  4. 参照の追加で、Microsoft.Device.Sensors と Microsoft.Xna.Framework を追加

MainPage.xaml.cs を開いて以下の項目を追加する(timer.Tick や CurrentValueChanged は+=を押してtabキーを2回押す)

using Microsoft.Devices.Sensors;
using System.Windows.Threading;
using Microsoft.Xna.Framework;

 

public partial class MainPage : PhoneApplicationPage
{
    Accelerometer acc = new Accelerometer();
    DispatcherTimer timer = new DispatcherTimer();

    // コンストラクター
public MainPage()
{
InitializeComponent();
        acc.CurrentValueChanged += new EventHandler<SensorReadingEventArgs<AccelerometerReading>>(acc_CurrentValueChanged);
acc.Start();

        timer.Interval = TimeSpan.FromSeconds(0.5);
timer.Tick += new EventHandler(timer_Tick);
    }

    void timer_Tick(object sender, EventArgs e)
{
        media.Pause();
PageTitle.Text = "Pause";
    }

    void acc_CurrentValueChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e)
{
        Vector3 a = e.SensorReading.Acceleration;
double d = Math.Max(Math.Max(Math.Abs(a.X), Math.Abs(a.Y)), Math.Abs(a.Z));

        if (d > 1.5)
{
Dispatcher.BeginInvoke(() =>
{
if (timer.IsEnabled)
timer.Stop();

                PageTitle.Text = "Play";
media.Play();
timer.Start();
});
}
    }
}