How do I programmatically play an MP3 on an iPhone?

后端 未结 4 1508
無奈伤痛
無奈伤痛 2020-12-16 03:30

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 thos

4条回答
  •  情歌与酒
    2020-12-16 03:49

    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 
    #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...

提交回复
热议问题