【问题标题】:Play sound when app is in background or screen is locked当应用程序处于后台或屏幕锁定时播放声音
【发布时间】:2015-04-28 12:58:27
【问题描述】:

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

UIBackgroundModes Array
Item0 String audio

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

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];

【问题讨论】:

  • 播放声音的代码,看起来如何?您是否导入了 MediaPlayer 框架?
  • 是的,很抱歉忘记了这一点:P 编辑了我的问题,这是我用来播放声音的代码,它在应用程序运行时工作正常,但如果应用程序进入后台或屏幕被锁定不'玩不了

标签: objective-c


【解决方案1】:

我只有一个 Swift 代码的 sn-p,但应该很容易将其转换为 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"];

【讨论】:

  • 我对 swift 不太了解,但我会尝试转换它:P ty
【解决方案2】:
// 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"];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-28
    • 2017-05-24
    • 2014-11-12
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 2019-05-27
    相关资源
    最近更新 更多