IOS 播放本地音乐(播放内存卡中的MP3) 及 文件的写入

来源:互联网 发布:9.20版本907工程数据 编辑:程序博客网 时间:2024/05/21 04:19

在IOS开发中, 每一个应用程序都拥有一个Documents的文件夹来存放自己的文件。

在这里为了测试, 我们首先得把mp3文件导入到项目中。

然后读出资源里的mp3文件,写入到documents中, 然后再从documents中读取该mp3文件来播放。

(在实际当中也许我们需要下载一首歌到本地文件, 然后播放它)


//先获取资源文件路径,然后转换成NSData写入到指定文件夹中

- (IBAction)ClickSave:(id)sender{    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"qyqx" ofType:@"mp3"]];    NSData *data = [[NSData alloc] initWithContentsOfURL:url];        NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/qyqx.mp3"];        [data writeToFile:filePath atomically:YES];}


//使用AVAudioPlayer来播放指定音乐
- (IBAction) ClickPly:(id)sender {        NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/qyqx.mp3"];        _myPlay = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:filePath] error:nil];        [_myPlay play];}


//AVAudioPlayer 必须在h文件中定义, 否则播放不了音乐

原创粉丝点击