AVAudioPlayer播放本地音乐AVPlayer播放网络音乐

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    /*----------AVAudioPlayer----------*/
//    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"浮夸" ofType:@"mp3"];
//    
//    //构建URL,要使用fileURLWithPath
//    NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
//    
//    NSError *error = nil;
//    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:&error];
//    audioPlayer.delegate = self;
//    // 分配播放所需的资源,并将其加入内部播放队列
//    [audioPlayer prepareToPlay];
//    
//    //设置当前播放的时间
//    [audioPlayer setCurrentTime:250];
    
    //后台播放音乐,设置音频的会话类型。必须真机演示
    AVAudioSession *ausioSession = [AVAudioSession sharedInstance];
    [ausioSession setCategory:AVAudioSessionCategoryPlayback error:NULL];
    
    
    
    /*---------AVPlayer-------------*/
    NSURL *url = [NSURL URLWithString:@"http://yinyueshiting.baidu.com/data2/music/121859548/1201250291406001661128.mp3?xcode=296f7746a300c412bedf6f0db640bd7aaf56297aed761ad4"];
    AVPlayer *avPlayer = [[AVPlayer alloc] initWithURL:url];
    [avPlayer play];
    
    /*-----------播放系统声音----------*/
//    
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"44th Street Medium" ofType:@"caf"];
//    NSURL *url = [NSURL fileURLWithPath:path];
//    //为声音文件注册为系统声音
//    AudioServicesCreateSystemSoundID((CFURLRef)url, &soundID);
//    
//    //播放系统声音
//    AudioServicesPlaySystemSound(soundID);
}


- (IBAction)playAction:(UIButton *)sender {
    //判断如果正在播放
    if (audioPlayer.isPlaying) {
        //暂停
        [audioPlayer pause];
        [sender setTitle:@"播放" forState:UIControlStateNormal];
    }else
    {
        [audioPlayer play];
        [sender setTitle:@"暂停" forState:UIControlStateNormal];
    }
}

- (IBAction)stopAction:(UIButton *)sender {
    [audioPlayer setCurrentTime:0];
    [audioPlayer pause];
    [audioPlayer stop];
}

- (IBAction)shakeAction:(UIButton *)sender {
    //震动
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}

#pragma -mark AVAudioPlayerDelegate
//完成播放的时候调用
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    NSLog(@"完成播放");
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值