本文實例為大家分享了iOS音樂播放器制作的具體代碼,供大家參考,具體內容如下
效果圖
目錄結構
代碼
//// ViewController.m// 播放音樂//// Created by xubh on 2017/3/24.// Copyright © 2017年 xubh. All rights reserved.//#import "ViewController.h"#import <AVFoundation/AVFoundation.h>@interface ViewController ()@property (weak, nonatomic) IBOutlet UIImageView *bgImageview;@property (strong,nonatomic) AVPlayer *player;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad];// 背景圖片和設備屏幕一樣大 CGRect r = [ UIScreen mainScreen ].applicationFrame; self.bgImageview.frame = r; // Do any additional setup after loading the view, typically from a nib.// 毛玻璃效果 UIToolbar *toolbar = [[UIToolbar alloc]init]; toolbar.frame = self.bgImageview.bounds; toolbar.barStyle = UIBarStyleBlack; toolbar.alpha = 0.9; [self.bgImageview addSubview:toolbar];// 創建播放器// NSString *path =[[NSBundle mainBundle]pathForResource:@"mysong1.mp3" ofType:nil ];// NSURL *url =[NSURL fileURLWithPath:path]; NSURL *url = [[NSBundle mainBundle] URLForResource:@"夜的樂章.mp3" withExtension:nil]; AVPlayerItem *playerItem = [[AVPlayerItem alloc]initWithURL:url]; self.player = [[AVPlayer alloc] initWithPlayerItem:playerItem];}//開始播放和暫停播放- (IBAction)startOrPauseMusic:(UIButton *)sender { switch (sender.tag) { case 3: [self.player play]; break; case 4: [self.player pause]; break; default: break; }}//切換歌曲- (IBAction)changeMusic:(UIButton *)sender { NSString *musicName =nil; switch (sender.tag) { case 1: musicName = @"告白氣球.mp3"; break; case 2: musicName = @"周杰倫串燒.mp3"; break; default: break; } NSURL *url = [[NSBundle mainBundle] URLForResource:musicName withExtension:nil]; AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithURL:url]; [self.player replaceCurrentItemWithPlayerItem:playerItem];// 播放音樂 [self.player play];}- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}@end
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答