zoukankan      html  css  js  c++  java
  • iOS AVAudioPlayer播放音乐

    一. AVAudioPlayer:       

                                  

        声明音乐控件AVAudioPlayer,必须声明为全局属性变量,否则可能不会播放,AVAudioPlayer只能播放本地音乐 

           //获取音乐文件路径
            NSURL *soundUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:_fileName ofType:@"mp3"]];
            
            if (!_BGMPlayer) {
                
                _asset = [[AVURLAsset alloc] initWithURL:soundUrl options:nil];
                //实例化音乐播放控件
                _BGMPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:_asset.URL error:nil];
            }
            if (_BGMPlayer != nil) {
                //缓冲播放
                _BGMPlayer.delegate = self;
                [_BGMPlayer prepareToPlay];
                _BGMPlayer.numberOfLoops = -1;
                [_BGMPlayer play];
            }else{
                NSLog(@"初始化失败");
            }
        

    二. AVURLAsset

      创建一个由URL标识的代表任何资源的asset对象

      

     _asset = [[AVURLAsset alloc] initWithURL:soundUrl options:nil];
                //实例化音乐播放控件
                _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:_asset.URL error:nil];

    三. AVAudioPlayerDelegate 

    /* audioPlayerBeginInterruption: is called when the audio session has been interrupted while the player was playing. The player will have been paused. */
    //产生中断后调用这个函数,通常暂停播放
    - (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player
    {
        [self.playerpause];
    }
    
    /* audioPlayerEndInterruption:withOptions: is called when the audio session interruption has ended and this player had been interrupted while playing. */
    /* Currently the only flag is AVAudioSessionInterruptionFlags_ShouldResume. */
    //恢复中断后调用这个函数,继续播放
    - (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags
    {
        [self.playerplay];
    }
    
    //解码出错后调用这个函数
    - (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
    
    //播放结束后调用这个函数
    - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag

    四. 参考链接

      http://www.cnblogs.com/QianChia/p/5771149.html

      http://www.jianshu.com/p/cc79c45b4ccf

      http://www.360doc.com/content/15/1214/23/20918780_520470043.shtml

      https://segmentfault.com/a/1190000004049416?_ea=471318

     

  • 相关阅读:
    Luogu P4071 [SDOI2016]排列计数
    CF 961E Tufurama
    Luogu P2057 [SHOI2007]善意的投票
    Luogu P2756 飞行员配对方案问题
    POJ2151
    POJ 3349&&3274&&2151&&1840&&2002&&2503
    POJ 2388&&2299
    EZ 2018 03 30 NOIP2018 模拟赛(六)
    POJ 1459&&3436
    BZOJ 1001: [BeiJing2006]狼抓兔子
  • 原文地址:https://www.cnblogs.com/roxy/p/5943770.html
Copyright © 2011-2022 走看看