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

     

  • 相关阅读:
    【BZOJ2329】括号修复(splay)
    连接数据库
    文件锁
    带进度条的输入流
    文件对话框
    使用Scanner来解析文件
    IO流(数据流
    IO流(随机流,数组内存流
    IO流文件字符输入输出流,缓冲流
    IO流(文件字节输入输出
  • 原文地址:https://www.cnblogs.com/roxy/p/5943770.html
Copyright © 2011-2022 走看看