본문 바로가기
IOS&Mac

AVAudioPlayer를 이용하여 IOS에서 음악재생, 음악정보 가져오기

by MOVE🔥 2017. 1. 20.
728x90
반응형

1. AVFoundation 라이브러리 추가


AVFoundation 프레임 워크를 추가한다.



소스에 #import <AVFoundation/AVFoundation.h> 를 추가한다.



2.  AVAudioPlayer 사용


NSString *path = [NSString stringWithFormat:@"%@/music%d.mp3", [[NSBundle mainBundle] resourcePath],playIndex];
    NSURL *soundUrl = [NSURL fileURLWithPath:path];
    audioplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
    [audioplayer play];


간단하다! url로 init을하고 play를 하면 특정 url의 노래를 play하게 된다.





3. 재생 music의 정보 가져오기


    AVAsset * assest = [AVURLAsset URLAssetWithURL:fileURL options:nil];
    NSString * musicTitle;
    NSString * musicArtist;
    UIImage * artworkImage;
    for (NSString *format in [assest availableMetadataFormats]) {
        for (AVMetadataItem *item in [assest metadataForFormat:format]) {

            if ([[item commonKey] isEqualToString:@"title"]) {
                musicTitle = (NSString *)[item value];
            }

            if ([[item commonKey] isEqualToString:@"artist"]) {
                musicArtist = (NSString *)[item value];
            }

            if ([[item commonKey] isEqualToString:@"artwork"]) {
                UIImage *img = nil;
                img = [UIImage imageWithData:[item.value copyWithZone:nil]];
                artworkImage = img;
            }
        }

    }


이 세가지 정보말고도 정의되어있는 음원에 대한 정보를 더 가져올 수 있다.






728x90
반응형

댓글