4

ipod ライブラリから曲を選択し、avplayer を使用して再生したい アプリがバックグラウンドになった後も音楽を再生し続けたい iOS プログラミングが初めてなので、誰か助けてもらえますか ..

ありがとう

4

1 に答える 1

7

ユーザーが自分の音楽ライブラリから1つまたは複数の曲を選択できるようにするには、MPMediaPickerControllerクラスを使用します。

-(void) pickSong {

    // Create picker view
    MPMediaPickerController* picker = [[MPMediaPickerController alloc] init];
    picker.delegate = self;

    // Check how to display
    if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) {

        // Show in popover
        [popover dismissPopoverAnimated:YES];
        popover = [[UIPopoverController alloc] initWithContentViewController:picker];
        [popover presentPopoverFromBarButtonItem:self.navigationItem.rightBarButtonItem permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];

    } else {

        // Present modally
        [self presentViewController:picker animated:YES completion:nil];

    }

}

self.navigationItem.rightBarButtonItemタイトルバーの右側にあるボタンから表示していない場合は変更します。

次に、デリゲートを実装して結果をリッスンする必要があります。

ユーザーが選択をキャンセルしたときに呼び出されます。

-(void) mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker {

    // Dismiss selection view
    [self dismissViewControllerAnimated:YES completion:nil];
    [popover dismissPopoverAnimated:YES];
    popover = nil;

}

ユーザーが何かを選択したときに呼び出されます。

-(void) mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection {

    // Dismiss selection view
    [self dismissViewControllerAnimated:YES completion:nil];
    [popover dismissPopoverAnimated:YES];
    popover = nil;

    // Get AVAsset
    NSURL* assetUrl = [mediaItemCollection.representativeItem valueForProperty:MPMediaItemPropertyAssetURL];
    AVURLAsset* asset = [AVURLAsset URLAssetWithURL:assetUrl options:nil];

    // Create player item
    AVPlayerItem* playerItem = [AVPlayerItem playerItemWithAsset:asset];

    // Play it
    AVPlayer* myPlayer = [AVPlayer playerWithPlayerItem:playerItem];
    [myPlayer play]; 

}

UIPopoverController* popover;クラスの.hファイルにが必要です。また、myPlayerどこかに保持する必要があります...

audio音楽をバックグラウンドで継続できるようにするには、キーの下のInfo.plistの配列に文字列を追加しUIBackgroundModesます。

于 2012-07-18T12:13:08.317 に答える