iPhone背景音乐播放器

Posted

技术标签:

【中文标题】iPhone背景音乐播放器【英文标题】:iPhone background music player 【发布时间】:2013-04-25 19:51:23 【问题描述】:

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

【问题讨论】:

【参考方案1】:

您可以使用 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

【讨论】:

太棒了,非常感谢。我看到你的文件类型为@“mp3”,但我应该把我拥有的歌曲的实际名称放在哪里,比如@“背景音乐”? 我分享了一个playMusicFile函数,如果你想播放backgroundmusic.mp3,可以这样调用:[self playMusicFile:@"backgroundmusic"]。【参考方案2】:

AVPlayerAVAudioPlayer 应该可以工作。

【讨论】:

以上是关于iPhone背景音乐播放器的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 MPMediaItem 属性持久 ID 在 iPhone 音乐播放器框架中播放音乐?

如何在 iPhone 游戏中播放背景音乐? [复制]

iphone app允许背景音乐继续播放

如何在 iPhone 的锁定屏幕中开始播放音乐

在 iPhone 上:找出当前正在播放的歌曲? (在 iPod 音乐播放器中)[重复]

Spritekit 在游戏时保留 iPhone 音乐