繁体   English   中英

如何以编程方式在iPhone上播放MP3?

[英]How do I programmatically play an MP3 on an iPhone?

我想在我的应用程序中加入一个MP3并按需播放。 不幸的是,我不知道如何开始。 我一直在阅读.caf文件,但我不确定它们是什么。

如果可能的话,我正在寻找一步一步。

以下是我在xCode 4.2中播放mp3的过程:

1)将AVFoundation.framework框架导入您的项目

2)在项目ViewController.h文件中添加: #import "AVFoundation/AVAudioPlayer.h"

#import <UIKit/UIKit.h>
#import "AVFoundation/AVAudioPlayer.h"

@interface ViewController : UIViewController

@end

3)将mp3文件yoursoundfile.mp3到根项目资源管理器中

4)在ViewController.m修改-(void)viewDidLoad

- (void)viewDidLoad{
    [super viewDidLoad];
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
                                         pathForResource:@"yoursoundfile"
                                         ofType:@"mp3"]];
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]
                                  initWithContentsOfURL:url
                                  error:nil];
    [audioPlayer play];
}

一旦你开始你的程序,它将播放声音。 您可以通过更改音量或何时播放,停止来自定义以适合您的应用...

您还可以尝试AVAudioPlayer实用程序框架。

在终端中使用afconvert将MP3转换为.caf。 男人afconvert会告诉你更多。

然后

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: name ofType: @"caf"];

NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];

AVAudioPlayer *player = [super initWithContentsOfURL: fileURL error: nil];
[fileURL release];
[player play];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM