当应用在后台或屏幕被锁定时播放声音

时间:2015-04-28 12:58:27

标签: objective-c

我有一个定时器,当时间到达0时播放声音,但现在我无法理解如何在应用程序处于后台模式或屏幕被锁定的情况下触发事件以播放声音,我找到了什么在网上搜索是在我的.plist文件中设置“UIBackgroundModes”,并添加“audio”作为数组成员。

UIBackgroundModes Array
Item0 String audio

然后在app中添加委托以下代码:

NSError *setCategoryErr = nil;
NSError *activationErr  = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];
[[AVAudioSession sharedInstance] setActive:YES error:&activationErr];

但声音没有播放..所以我想知道是否可以做这样的事情或者我应该改变方法

修改

我导入了:

#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>

这是我用来创建声音的代码:

AVAudioPlayer *player;
NSString *soundFilePath = [NSString stringWithFormat:@"%@/clock.mp3",
                               [[NSBundle mainBundle] resourcePath]];
    NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];

    player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL
                                                                   error:nil];
    player.numberOfLoops = -1;

    dispatch_async(dispatch_get_main_queue(), ^{
        [player prepareToPlay];
    });

然后播放:

[player play];

2 个答案:

答案 0 :(得分:1)

我只有一小段Swift代码,但很容易将其转换为Obj-C

尝试使用AVPlayerItem init with URL,然后设置AVPlayer init with PlayerItem

let assetUrl = self.nowPlayingItem!.associatedItem!.valueForProperty(MPMediaItemPropertyAssetURL) as! NSURL
let playerItem = AVPlayerItem(URL: assetUrl)

if let player = self.player {
    player.replaceCurrentItemWithPlayerItem(playerItem)
} else {
    self.player = AVPlayer(playerItem: playerItem)
}
self.player!.play() 

以及这行代码:

NSString *soundFilePath = [NSString stringWithFormat:@"%@/clock.mp3",
                               [[NSBundle mainBundle] resourcePath]];

你试过了吗?

[[NSBundle mainBundle] URLForResource:@"song" withExtension:@"mp3"];

答案 1 :(得分:-1)

// Create a new player item
    NSURL *assetUrl = [nowPlayingItem valueForProperty:MPMediaItemPropertyAssetURL];
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:assetUrl];

    // Either create a player or replace it
    if (self.player) {
        [self.player replaceCurrentItemWithPlayerItem:playerItem];
    } else {
        self.player = [AVPlayer playerWithPlayerItem:playerItem];
    }

nowPlayingItem在这里是一个MPMediaItem但只是将NSURL *assetUrl = [nowPlayingItem valueForProperty:MPMediaItemPropertyAssetURL];替换为NSURL *assetUrl =[[NSBundle mainBundle] URLForResource:@"song" withExtension:@"mp3"];