iPhone背景音乐播放器

标签 iphone ios objective-c background-music

任何人都可以指导我查看教程,或者向我展示播放背景音乐的实际代码。我需要它才能启动和停止。这不是作业,所以你知道。我的作业已经完成,我只是想给它添加音乐,但我不知道该怎么做。谢谢!

最佳答案

你可以使用 AVAudioPlayer

//You have to import AvFoundation to use AVAudioPlayer
#import <AVFoundation/AVFoundation.h>

-(void) playMusicFile:(NSString *) songName
{   
    NSString *musicFile = [[NSBundle mainBundle] pathForResource:songName ofType:@"mp3"];

    NSError *soundError = nil;
    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:musicFile] error:&soundError];
    if(self.audioPlayer == nil)
    {
        NSLog(@"%@",soundError);
    }
    else
    {
        //Delegation is optional but it helps you do stuff after song finished playing etc
        [self.audioPlayer setDelegate:self];
        //Set number of repeats, 0 is default plays once, negative values makes it play infinitely
        [self.audioPlayer setNumberOfLoops:0];
        //Prepare to play is not always necessary, but otherwise it can take time to play
        [self.audioPlayer prepareToPlay];
        [self.audioPlayer play];
    }
}

//This is the delegate called after the song finished playing, you can use it to play other songs, or do other stuff
-(void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    ...
}

停止和暂停:

//You can easily stop and pause using: 
[self.audioPlayer stop]; //Stop doesn't work as you would expect. It doesn't set the current time to 0 but only undoes the setup you had with the audioplayer.
[self.audioPlayer pause];

//It is possible to call [self.audioPlayer play] after each method and playback will continue from where it left off.

有关更多信息,请访问引用资料:http://developer.apple.com/library/ios/#DOCUMENTATION/AVFoundation/Reference/AVAudioPlayerClassReference/Reference/Reference.html

关于iPhone背景音乐播放器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16223548/

相关文章:

ios - 如何在 Objective-C 中更改垃圾按钮的颜色?

objective-c - 如何在 objective-c 中以编程方式设置图像位置?

ios - iOS 控制中心是否调用任何 UIApplication 方法。?

iphone - 如何将 gif 动图保存到我的相册?

iphone - 如何在 cocoa-touch 中以正确的方式解码 urlstring?

iphone - 如何使用 UIImageView 和 UILabel 创建 UIBarButtonItem

ios - UITableViewCell自定义编辑内容

ios - 子类化自定义UICollectionViewLayout实现一定的删除和插入效果

iphone - iOS 应用程序为调用添加前缀

ios - 在 UITableView 的表格部分下添加文本