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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1296786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 03:06:57  来源:igfitidea点击:

How do I programmatically play an MP3 on an iPhone?

iphonexcodeaudio

提问by AngryHacker

I'd like to include an MP3 with my app and play it on demand. Unfortunately I am not sure how to get started. I keep reading about .caf files, but I am not sure what those are.

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

I am looking for a step by step, if possible.

如果可能的话,我正在寻找一个循序渐进的方法。

采纳答案by fbrereto

You could also try the AVAudioPlayerutility Framework.

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

回答by DavidNg

Here is what I am doing to play mp3 in xCode 4.2:

这是我在 xCode 4.2 中播放 mp3 所做的工作:

1) Import AVFoundation.frameworkframework into your project

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

2) Adding: #import "AVFoundation/AVAudioPlayer.h"into your project ViewController.hfile:

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

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

@interface ViewController : UIViewController

@end

3) Drag and drop your mp3 file yoursoundfile.mp3into your root project explorer

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

4) Modify -(void)viewDidLoadin ViewController.m:

4)修改-(void)viewDidLoadViewController.m

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

As soon as you start your program, it will play the sound. You can customize to fit your app by changing volume, or when to play, stop...

只要您启动程序,它就会播放声音。您可以通过更改音量或播放时间、停止时间来自定义以适合您的应用程序...

回答by mahboudz

Use afconvert in Terminal to convert your MP3 to a .caf. man afconvert will tell you more.

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

Then

然后

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