前回の続きです
【iOS】iPod Library Accessの使い方(4)任意の曲を検索して再生する
さて今回はとうとう最終回。非公開のUIDictationControllerなる音声入力のライブラリを使ってこれまで作ってきたiPodを操作してみました。動画がこちらです。
コード
githubにもソースを全部置いたので、大事そうなところだけ。さっき動いたばかりなのでバグはいっぱいあります。
https://github.com/jojonki/iOS/tree/master/JPlayer
VoiceInputView
UIViewを実装するカスタマイズビューを自分で作り、メインのビューに突っ込みます。これはアプリ内で擬似的にキーボードを表示する役割がありますが、ユーザーには見える必要がないのでHiddenのチェックが入っています。
UITextInputの最低限必要な関数を実装するんですが、重要なのはこの辺。録音が終わったとか、結果を受け取ったとかのイベントを受け取ることができるので、JPlayerViewControllerにそのことを通知します。
- (void)insertDictationResult:(NSArray *)dictationResult {
NSLog(@"insertDictationResult");
[
[NSNotificationCenter defaultCenter]
postNotificationName:DictationRecognitionSucceededNotification
object:self
userInfo:[NSDictionary dictionaryWithObject:dictationResult forKey:DictationResultKey]
];
}
- (void)dictationRecordingDidEnd {
NSLog(@"dictationRecordingDidEnd");
[
[NSNotificationCenter defaultCenter]
postNotificationName:DictationRecordingDidEndNotification
object:self
];
}
- (void)dictationRecognitionFailed {
NSLog(@"dictationRecognitionFailed");
[
[NSNotificationCenter defaultCenter]
postNotificationName:DictationRecognitionFailedNotification
object:self
];
}
JPlayerViewController
非公開ライブラリのUIDictationControllerさんを定義します。startDictationとstopDictaitonが認識開始と停止の関数です、簡単ですね。
あ、_textInputViewはVoiceInputViewなのでそれをFirstResponderにしておくことをお忘れなく。
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
if (![_textInputView isFirstResponder]) {
[_textInputView becomeFirstResponder];
}
_dictationController =
[NSClassFromString(@"UIDictationController") performSelector:@selector(sharedInstance)];
}
- (void)startDictation {
[_dictationController performSelector:@selector(startDictation)];
}
- (void)stopDictation {
[_dictationController performSelector:@selector(stopDictation)];
}
認識結果をもとにアーティスト名、曲名で検索かけて、検索結果を再生キューにセットして音楽を再生します。
- (void)playSongWithArtistName: (NSString *)artistName {
MPMediaPropertyPredicate *artistNamePredicate =
[ MPMediaPropertyPredicate predicateWithValue:artistName
forProperty:MPMediaItemPropertyArtist];
MPMediaQuery *query = [MPMediaQuery artistsQuery];
[query addFilterPredicate:artistNamePredicate];
if (0 != [[query items] count]) {
[_player setQueueWithQuery:query];
[_player setShuffleMode:MPMusicShuffleModeSongs];
[_player play];
}
}
- (void)playSongWithSongName: (NSString *)titleName {
MPMediaPropertyPredicate *titleNamePredicate =
[MPMediaPropertyPredicate predicateWithValue:titleName
forProperty:MPMediaItemPropertyTitle];
MPMediaQuery *query = [MPMediaQuery artistsQuery];
[query addFilterPredicate:titleNamePredicate];
if (0 != [[query items] count]) {
[_player setQueueWithQuery:query];
[_player setShuffleMode:MPMusicShuffleModeSongs];
[_player play];
}
}
最後に
iPod Library Accessの紹介はこれで終わりです。最後の回は異色で、いろいろ説明を省いてしまって申し訳ないです。ソースはぜんぶあるのでここまで来た人なら、ソースを自分で追った方が早いと思ったので。
それでは、アデュー。