Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

iphone - How do you make a sound file play automatically thought an iOS app and loop using Objective-C?

I am making a game for iPhone using objective-c. I have the music I want to play in a file in the project. I need to know how to make it begin playing when the app launches, and loop at the end. Does anyone know how to do this? Code examples would be great! Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you can use AVAudioPlayer in App Delegate.

First in your App Delegate .h file add these lines:

#import <AVFoundation/AVFoundation.h>

and these one:

AVAudioPlayer *musicPlayer;

In your .m file add this method:

- (void)playMusic {

    NSString *musicPath = [[NSBundle mainBundle] pathForResource:@"phone_loop" ofType:@"wav"];
    NSURL *musicURL = [NSURL fileURLWithPath:musicPath];

    musicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:nil];
    [musicPlayer setNumberOfLoops:-1];   // Negative number means loop forever

    [musicPlayer prepareToPlay];
    [musicPlayer play];
}

Finally call it in the didFinishLaunchingWithOptions method:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  ...
  [self playMusic];
  ...
}

If you want to stop the music just:

[musicPlayer stop];

Aditionally you can check the Apple Documentation for AVAudioPlayer delegate for Handling Audio Interruptions http://developer.apple.com/library/ios/#DOCUMENTATION/AVFoundation/Reference/AVAudioPlayerDelegateProtocolReference/Reference/Reference.html

PS: Remember to import the AVFoundation Framework to your project.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...