How do I programmatically play an MP3 on an iPhone?

混江龙づ霸主 提交于 2019-11-27 16:26:13

问题


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.

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


回答1:


You could also try the AVAudioPlayer utility Framework.




回答2:


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

1) Import AVFoundation.framework framework into your project

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

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

@interface ViewController : UIViewController

@end

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

4) Modify -(void)viewDidLoadin ViewController.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...




回答3:


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

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



回答4:


Maybe look at: http://iphoneincubator.com/blog/audio-video/simple-way-to-play-mp3-audio-files and http://cocoawithlove.com/2008/09/streaming-and-playing-live-mp3-stream.html?



来源:https://stackoverflow.com/questions/1296786/how-do-i-programmatically-play-an-mp3-on-an-iphone

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!