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];

     

     

  • 相关阅读:
    java获取本机IP和主机名
    SSH框架总结(框架分析+环境搭建+实例源代码下载)
    Centos7安装mysql8教程
    jquery 操作HTML data全局属性缓存的坑
    mysql协议分析2---认证包
    mysql协议分析1---报文的格式和基本类型
    TCP三次握手抓包理解
    java读写文件小心缓存数组
    spring 事务隔离级别导致的bug
    mysql 不同版本下 group by 组内排序的差异
  • 原文地址:https://www.cnblogs.com/jiangshiyong/p/2536260.html
Copyright © 2011-2022 走看看