1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using NAudio.Wave;
using NAudio.Dsp;
using Microsoft.Win32;
using System.Runtime.CompilerServices;
using Forms = System.Windows.Forms;
using System.IO;
using System.Windows.Threading;
namespace DesktopMusicPlayer
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// ウィンドウをマウスのドラッグで移動できるようにする
this.MouseLeftButtonDown += (sender, e) => this.DragMove();
isPlaying = false;
fileNamesIndex= 0;
}
/* グローバル変数 */
private string basePath; //音楽ファイルを格納しているフォルダのパス
private string[] fileNames = null; //音楽ファイルの名前
private bool isPlaying; //再生中かどうかのフラグ 再生/ポーズボタン用のフラグ
private int fileNamesIndex; //fileNamesのindex
private WaveOut outputDevice; //音楽プレイヤー
private AudioFileReader audioStream; //フーリエ変換前の音楽データ
private readonly long reciprocal_of_FPS = 167000; //60(fps)の逆数 (100ns)
private float[,] result; //フーリエ変換後の音楽データ
private DispatcherTimer timer = null; //タイマー割り込みに使用するタイマー
private Line[] bar; //音声波形表示に使用するLine(バー)
private Brush brush; //音声波形表示のLine(バー)に使用するブラシ
private int bytePerSec; //1秒当たりのバイト数
private int musicLength_s; //音楽の長さ (秒)
private int playPosition_s; //再生位置 (秒)
private int drawPosition; //音声波形表示位置
private bool barDrawn = false; //描画済みのLine(バー)があるかを示すフラグ (生成済み = true, 未生成 = false)
private DispatcherTimer loopTimer= null; //音楽再生ループ用タイマ
//private bool isFolderChange = false; //BasePathを変更した直後かどうかを判定するフラグ
private void click_buttonReturn(object sender, RoutedEventArgs e)
{
/* BasePath未入力 or MP3ファイルのないパスを選択した場合は何もしない */
if (fileNames == null || fileNames.Length == 0)
{ return; }
/* 連打防止の為にボタンを無効化 */
buttonReturn.IsEnabled = false;
/* 連打防止の為にボタンを有効化 */
buttonReturn.IsEnabled = true;
}
private void click_buttonStartandPause(object sender, RoutedEventArgs e)
{
/* BasePath未入力 or MP3ファイルのないパスを選択した場合は何もしない */
if (fileNames == null || fileNames.Length == 0)
{ return; }
/* 連打防止の為にボタンを無効化 */
buttonStartPause.IsEnabled = false;
if (isPlaying)
{
/* 再生中のとき => ポーズ状態へ以降 */
pauseAudio(); //音楽を一時停止
buttonStartPause.Content = "再生";
isPlaying = false;
}
else
{
/* ポース中のとき => 再生状態へ以降 */
startAudio(); //音楽を再生
buttonStartPause.Content = "停止";
isPlaying = true;
//loopTimer.Start();
//if (isFolderChange)
//{
// isFolderChange = false;
//}
}
/* 連打防止の為にボタンを有効化 */
buttonStartPause.IsEnabled = true;
}
private void click_buttonNext(object sender, RoutedEventArgs e)
{
/* BasePath未入力 or MP3ファイルのないパスを選択した場合は何もしない */
if (fileNames == null || fileNames.Length == 0)
{ return; }
/* 連打防止の為にボタンを無効化 */
buttonNext.IsEnabled = false;
/* 曲を停止 */
outputDevice.Stop();
/* 本関数の中では楽曲の停止のみを行う。
* 楽曲を停止することでloopTimer_tick()内の処理が実行され、、
* looptimer_tickの停止→インデックス更新→setAudioRender()→再生まで行ってくれる。
*/
/* 連打防止の為にボタンを有効化 */
buttonNext.IsEnabled = true;
}
private void click_buttonBrowser(object sender, RoutedEventArgs e)
{
/* フォルダを選択させる */
var folderBrowserDialog = new Forms.FolderBrowserDialog();
folderBrowserDialog.Description = "MP3ファイルを格納しているフォルダーを選択してください。";
if(folderBrowserDialog.ShowDialog() == Forms.DialogResult.OK)
{
basePath = folderBrowserDialog.SelectedPath;
textboxBasePath.Text = basePath;
//isFolderChange= true;
fileNamesIndex = 0;
if (isPlaying)
{
/* 再生中の場合は楽曲を停止してUIを初期状態に戻す */
loopTimer.Stop(); //自動再生監視用のTimerTickを先に停止
outputDevice.Stop(); //楽曲を停止
isPlaying= false;
buttonStartPause.Content = "再生";
}
}
else
{
/* OK以外のときはリターンする */
return;
}
/* 選択したパス内のMP3ファイルを取得する */
fileNames = Directory.GetFiles(basePath, "*.mp3", SearchOption.AllDirectories);
/* 音楽を再生する前準備 */
setAudioRender();
}
private void setAudioRender()
{
barDrawn = false;
/* 音楽終了監視用TimerTick */
loopTimer = new DispatcherTimer(DispatcherPriority.Normal);
loopTimer.Interval = new TimeSpan(10000000); //停止判定する間隔を1秒
loopTimer.Tick += new EventHandler(looptimer_tick);
// ファイル名の拡張子によって、異なるストリームを生成
audioStream = new AudioFileReader(fileNames[fileNamesIndex]);
// プレーヤーの生成
outputDevice = new WaveOut();
// 音楽ストリームの入力
outputDevice.Init(audioStream);
//if (!isFolderChange)
// loopTimer.Start();
/* 波形表示描画用のTimerTick */
timer = new DispatcherTimer(DispatcherPriority.Normal);
timer.Interval = new TimeSpan(reciprocal_of_FPS);
timer.Tick+= new EventHandler(timer_Tick);
result = FFT_HammingWindow_ver1();
// 音声波形表示に使用するLine(バー)の配列を確保 (この時点では、コンストラクタは呼び出されていない)
gridWaveArea.Children.Clear();
bar = new Line[result.GetLength(1)];
for (int i = 0; i < result.GetLength(1); i++)
{
bar[i] = new Line(); // 各要素のコンストラクタを明示的に呼び出す
}
// Line(バー)に使用するブラシ
brush = new SolidColorBrush(Color.FromArgb(128, 61, 221, 200));
// 1秒あたりのバイト数を計算
bytePerSec = (audioStream.WaveFormat.BitsPerSample / 8) * audioStream.WaveFormat.SampleRate * audioStream.WaveFormat.Channels;
// 音楽の長さ (秒)を計算
musicLength_s = (int)audioStream.Length / bytePerSec;
// コンストラクタを呼んだ際に、Positionが最後尾に移動したため、0に戻す
audioStream.Position = 0;
}
/// <summary>
/// 音楽の波形データにハミング窓をかけ、高速フーリエ変換する
/// </summary>
/// <returns>フーリエ変換後の音楽データ</returns>
private float[,] FFT_HammingWindow_ver1()
{
// 波形データを配列samplesに格納
float[] samples = new float[audioStream.Length / audioStream.BlockAlign * audioStream.WaveFormat.Channels];
audioStream.Read(samples, 0, samples.Length);
//1サンプルのデータ数
int fftLength = 256;
//1サンプルごとに実行するためのイテレータ用変数
int fftPos = 0;
// フーリエ変換後の音楽データを格納する配列
float[,] result = new float[samples.Length / fftLength, fftLength / 2];
// 波形データにハミング窓をかけたデータを格納する配列
Complex[] buffer = new Complex[fftLength];
for (int i = 0; i < samples.Length; i++)
{
// ハミング窓をかける
buffer[fftPos].X = (float)(samples[i] * FastFourierTransform.HammingWindow(fftPos, fftLength));
buffer[fftPos].Y = 0.0f;
fftPos++;
// 1サンプル分のデータが溜まったとき
if (fftLength <= fftPos)
{
fftPos = 0;
// サンプル数の対数をとる (高速フーリエ変換に使用)
int m = (int)Math.Log(fftLength, 2.0);
// 高速フーリエ変換
FastFourierTransform.FFT(true, m, buffer);
for (int k = 0; k < result.GetLength(1); k++)
{
// 複素数の大きさを計算
double diagonal = Math.Sqrt(buffer[k].X * buffer[k].X + buffer[k].Y * buffer[k].Y);
double intensityDB = 10.0 * Math.Log10(diagonal);
const double minDB = -60.0;
// 音の大きさを百分率に変換
double percent = (intensityDB < minDB) ? 1.0 : intensityDB / minDB;
// 結果を代入
result[i / fftLength, k] = (float)diagonal;
}
}
}
return result;
}
private void looptimer_tick(object sender, EventArgs e)
{
if (outputDevice.PlaybackState == PlaybackState.Stopped)
{
loopTimer.Stop();
updateFileNamesIndex();
setAudioRender();
if(isPlaying)
startAudio();
}
}
private void updateFileNamesIndex()
{
updateFileNamesIndex_next();
}
private void updateFileNamesIndex_next()
{
fileNamesIndex++;
if(fileNamesIndex == fileNames.Length)
{
fileNamesIndex= 0;
}
}
private void updateFileNamesIndex_random()
{
}
/// <summary>
/// Timer.Tickが発生したときのイベントハンドラ
/// </summary>
/// <param name="sender">イベント送信元</param>
/// <param name="e">イベント引数</param>
private void timer_Tick(object sender, EventArgs e)
{
// この中の処理はメインスレッドで行われる
// 再生位置 (秒)を計算
playPosition_s = (int)audioStream.Position / bytePerSec;
// 音声波形表示を描画する配列のオフセット(インデックス)を計算
drawPosition = (int)(((double)audioStream.Position / (double)audioStream.Length) * result.GetLength(0));
Make_AudioSpectrum();
}
/// <summary>
/// 音声波形表示を描画
/// </summary>
private void Make_AudioSpectrum()
{
// 描画済みのLine(バー)がある場合
if (barDrawn)
{
for (int j = 0; j < result.GetLength(1); j++)
{
// 画面からLine(バー)を削除
gridWaveArea.Children.Remove(bar[j]);
}
}
if (drawPosition >= result.GetLength(0)) // マネージリソース(Line bar[])の解放は自動でガベージコレクションが行う
return;
for (int j = 0; j < result.GetLength(1);)
{
// 描画する方法 (Brush)を設定
bar[j].Stroke = brush; // System.Windows.Media.Brushes.LightBlue;
// (親要素内に作成されるときに適用される)水平方向の配置特性を、(親要素のレイアウトのスロットの)左側に設定
bar[j].HorizontalAlignment = HorizontalAlignment.Left;
// (親要素内に作成されるときに適用される)垂直方向の配置特性を、(親要素のレイアウトのスロットの)中央に設定
bar[j].VerticalAlignment = VerticalAlignment.Center;
// 始点のx座標を設定
bar[j].X1 = j * 7 + 32;
// 終点のx座標を設定
bar[j].X2 = j * 7 + 32;
// 始点のy座標を設定
bar[j].Y1 = 0;
// 終点のy座標を設定 (result[,]は、0 ~ 1の値)
bar[j].Y2 = 7700 * result[drawPosition, j];
// 長さが400より大きい場合は長さを400にする
if (bar[j].Y2 >= 400)
bar[j].Y2 = 400;
// 幅を設定
bar[j].StrokeThickness = 5;
// 画面にLine(バー)を追加
gridWaveArea.Children.Add(bar[j]);
j += 1;
}
// 描画済みにする
barDrawn = true;
}
private void startAudio()
{
// 音楽の再生 (おそらく非同期処理)
outputDevice.Play();
loopTimer.Start();
timer.Start();
}
private void pauseAudio()
{
//音楽の停止
outputDevice.Pause();
}
/// <summary>
/// コンテキストメニューのExitが押されたときのイベントハンドラ
/// </summary>
/// <param name="sender">イベント送信元</param>
/// <param name="e">イベント引数</param>
private void Quit_Clicked(object sender, RoutedEventArgs e)
{
Close();
}
}
}
|