zoukankan      html  css  js  c++  java
  • 使用AVFoundation播放音乐,并提取音乐封面显示

    1. 将mp3资源文件放在更目录下

    2.导入AVFoundation类

      #import <AVFoundation/AVFoundation.h>

    3.读取文件

       //获取资源目录

       NSString *resoucePath = [[NSBundle mainBundle]resourcePath];

       // 取出资源目录下所有mp3文件,将地址封装在数组中

       NSArray *mp3Array =          [NSBundlepathsForResourcesOfType:@"mp3"inDirectory[[NSBundlemainBundle]resourcePath]];

     

       NSMutableArray *musicArray;

     

       for (NSString *filePath in mp3Array) {

           

            //fileURLWithPath是初始化文件路径url得,urlWithPath是初始化网络链接得

            NSURL *fileURL = [NSURL fileURLWithPath:filePath];

            //初始化urlAssetoptions中可以指定要求准确播放时长

            AVURLAsset *avURLAsset = [AVURLAsset URLAssetWithURL:fileURL options:nil];

            [musicArray addObject:avURLAsset];

        }

     4.单元格中显示封面信息

       //取出每一行对应得AVURLAsset

        AVURLAsset *mp3Asset = [musicArray objectAtIndex:indexPath.row];

        NSLog(@"mp3Asset:%@",[[[mp3Asset   URL]absoluteString]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]);

        //取出url并取消百分号utf8转码

        NSString *mp3FilePath = [[[mp3Asset    URL]absoluteString]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

        //取最后一个/后面得路径

        NSString *musicTitle = [mp3FilePath lastPathComponent];

        //去掉.mp3得到歌曲名称

        musicTitle = [musicTitle substringToIndex:[musicTitle rangeOfString:@"."].location];

        musicCell.textLabel.text = musicTitle;

        for (NSString *format in [mp3Asset availableMetadataFormats]) {

            NSLog(@"-------format:%@",format);

            for (AVMetadataItem *metadataItem in [mp3Asset metadataForFormat:format]) {

                NSLog(@"commonKey:%@",metadataItem.commonKey);

                if ([metadataItem.commonKey isEqualToString:@"artwork"]) {

                    //取出封面artwork,从data转成image显示

                    musicCell.imageView.image = [UIImage imageWithData:[(NSDictionary*)metadataItem.value objectForKey:@"data"]];

                }

            }

        }

        //取得播放路径

        AVURLAsset *mp3Asset = [musicArray objectAtIndex:indexPath.row];

        //mp3文件路径得url

        NSURL *mp3URL = mp3Asset.URL;

    5. 调用AVAudioPlayer 播放文件

        #import <AVFoundation/AVFoundation.h>

        AVAudioPlayer *audioPlayer;

      audioPlayer = [[AVAudioPlayeralloc]initWithContentsOfURL:musicURLerror:NULL];

        [audioPlayerplay];

     

     

  • 相关阅读:
    Sublime2 Text编辑器使用技巧
    PHP实现一个简单url路由功能
    jQuery extend函数详解
    Memcached常用命令及使用说明
    根据一张表去更新另一张表
    npm ERR! Error: socket hang up
    Oracle中group by 1,order by 1的理解
    Oracle中的next_day(date,char)函数的理解
    WebService入门
    OCupload、POI、PinYin4j的简单入门
  • 原文地址:https://www.cnblogs.com/jiangshiyong/p/2536260.html
Copyright © 2011-2022 走看看