播放音乐
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController () <AVAudioPlayerDelegate> {
AVAudioPlayer *myAudioPlayer;
}
@property (weak, nonatomic) IBOutlet UILabel *artistLabel;
@property (weak, nonatomic) IBOutlet UILabel *albumLabel;
@property (weak, nonatomic) IBOutlet UIImageView *artworkImageView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setActive:YES error:nil];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"后会无期" ofType:@"mp3"];
NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:fileUrl options:nil];
NSString *format = [[asset availableMetadataFormats] firstObject];
for (AVMetadataItem *item in [asset metadataForFormat:format]) {
if ([item.commonKey isEqualToString:@"artist"]) {
self.artistLabel.text = (id)item.value;
}
else if ([item.commonKey isEqualToString:@"albumName"]) {
self.albumLabel.text = (id)item.value;
}
else if ([item.commonKey isEqualToString:@"artwork"]) {
NSData *data = (id)item.value;
self.artworkImageView.image = [UIImage imageWithData:data];
}
else if ([item.commonKey isEqualToString:@"title"]) {
}
}
myAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:nil];
myAudioPlayer.volume = 1;
[myAudioPlayer prepareToPlay];
[myAudioPlayer play];
myAudioPlayer.delegate = self;
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
}
@end