ios - 暂停音频文件以播放不同的音频文件

标签 ios objective-c avfoundation

我正在使用 systemMusicPlayer 在应用内播放歌曲。

如果用户在“正在播放” View 上按下 noiseButton,它将暂停 systemMusicPlayer 歌曲音频文件 10 秒以播放 noiseButton音频文件,然后在 systemMusicPlayer 歌曲音频文件上拾取。

我能够让 systemMusicPlayer 歌曲音频文件暂停,然后在 10 秒后恢复,但我无法获得 noiseButton 在 10 秒内播放声音。

  • 我知道 noiseButton 音频文件有效
  • 我在播放 noiseButton 文件的方法之前和之后进行 NSLogging

我不确定我错过了什么?

这是我的代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    musicPlayer = [MPMusicPlayerController systemMusicPlayer];
    [self registerMediaPlayerNotifications];

    // Construct URL to sound file
    NSString *path = [NSString stringWithFormat:@"%@/background-music-aac.caf", [[NSBundle mainBundle] resourcePath]];
    NSURL *soundUrl = [NSURL fileURLWithPath:path];

    // Create audio player object and initialize with URL to sound
    _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
}

- (void)willPlayClip {
    [NSTimer scheduledTimerWithTimeInterval:10.0
                                     target:self
                                   selector:@selector(willPlayMusicInTenSeconds:)
                                   userInfo:nil
                                    repeats:NO];
}

- (void)willPlayMusicInTenSeconds:(NSTimer *)timer {
    NSLog(@"Get ready to Play noise sound");
    [_audioPlayer play];
    NSLog(@"Play noise sound");

    [musicPlayer play];
    NSLog(@"Start playing again");
}

以及 noiseButton 内按下时的代码:

if ([musicPlayer playbackState] == MPMusicPlaybackStatePlaying) {
    [musicPlayer pause];
    NSLog(@"Paused!");
    [self willPlayClip];
} else {
    NSLog(@"Already paused");
}

最佳答案

您要设置什么 AudioSession 类别?如果不是,请参阅此文档:

Audio Session Categories

我相信,如果您将 session 设置为 AVAudioSessionCategoryAmbient,您应该会获得所需的行为:

The category for an app in which sound playback is nonprimary—that is, your app can be used successfully with the sound turned off.

This category is also appropriate for “play along” style apps, such as a virtual piano that a user plays while the Music app is playing. When you use this category, audio from other apps mixes with your audio. Your audio is silenced by screen locking and by the Silent switch (called the Ring/Silent switch on iPhone).

如果您还没有尝试过,请尝试一下。

关于ios - 暂停音频文件以播放不同的音频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37449389/

相关文章:

ios - 检查 NSString 是否为空/空的防弹方法是什么?

iphone - iPhone 在 Z 轴上时的 UIImage 方向

ios - 使用 MTKView 显示解码的视频流会导致不希望的模糊输出

objective-c - 动画 viewWillAppear 和 viewWillDisappear?

ios - Swift:CGPathRelease 和 ARC

ios - 带有数字键盘的 Flutter TextField,需要逗号而不是句点(仅限 iOS)

ios - 如何从不同的 View Controller 访问模型?

iphone - 检查 NSString 是否同时包含字母和数字

ios - 仅在按住按钮时扫描条形码

ios - Core Data 无法在 IOS Objective - C 中保存 UITextField 的数据