tvOS 应用程序不播放音频文件

tvOS app doesn't play audio file

我有一个 tvOS 应用试图播放这样的音频文件:

#import "NameViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface NameViewController ()

@end

@implementation NameViewController
- (void)viewDidLoad {
    [super viewDidLoad];

    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"intro" ofType:@"mp3"];
    NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL fileTypeHint:AVFileTypeMPEGLayer3 error:nil];
    player.numberOfLoops = -1; //infinite

    [player play];


}

如果我在[player play]之后放一个断点;它开始播放几秒钟。如果我没有断点,就不会播放任何音频。

我做错了什么?

我不太确定问题出在哪里,但是既然你说在 [player play]; 之后放置一个断点会导致音频播放,听起来好像系统正在尝试创建和播放音频播放器太快了...你 运行 这是在模拟器上还是在电视开发套件上?

也许尝试添加一个单独的方法来创建和播放播放器,就像这样,会给系统足够的时间来创建视图,然后然后创建和播放音频播放器?

- (void) createAndStartAudioPlayer {
  NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"intro" ofType:@"mp3"];
    NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL fileTypeHint:AVFileTypeMPEGLayer3 error:nil];
    player.numberOfLoops = -1; //infinite

    [player play];
}

然后从 viewDidLoad:

调用
[self createAndStartAudioPlayer];

这通过在 viewWillAppear 中调用播放来实现:

#import "NameViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface NameViewController ()
@property (strong, nonatomic) AVAudioPlayer *player;
@end

@implementation NameViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self createAndStartAudioPlayer];


}

- (void) viewWillAppear:(BOOL)animated{

    [self.player play];
}

- (void) createAndStartAudioPlayer {
    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"intro" ofType:@"mp3"];
    NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL fileTypeHint:AVFileTypeMPEGLayer3 error:nil];
    self.player.numberOfLoops = -1; //infinite


}

您的 AVAudioPlayer 需要在您的 ViewController 中定义为 属性,然后您可以从任何地方调用它。

AVAudioPlayer 在声音播放完毕之前被释放。当您在调用播放后设置断点时,音频播放器不会被释放,直到您继续播放,所以声音会继续播放。如果您将音频播放器设为 属性,例如:@property (strong, nonatomic) AVAudioPlayer *player; 那么在您的视图控制器被删除之前,它不会被释放。