ios - iOS背景音乐问题

标签 ios xcode audio

这个问题已经在这里有了答案:




已关闭8年。




Possible Duplicate:
iOS SDK : playing music on the background and switching views



嗨,大家好,我当前正在使用此代码在应用启动时在我的应用中播放背景音乐。但是当我将 View 切换到SecondView并返回到Firstview时,音乐会重新开始并与当前正在播放的音乐重叠,并且在播放时会保持重叠的音乐我返回到Firstview,当我从SecondView切换回Firstview时,如何重新播放音乐。

FirstViewController.m
- (void)viewDidLoad {
  NSString *path = [[NSBundle mainBundle] pathForResource:@"drums" ofType:@"mp3"];
  theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPathath] error:NULL];
  theAudio.delegate = self;
  theAudio.numberOfLoops = -1;
  [theAudio play]; 

最佳答案

您可以使用NSUserDefaults保存音乐的播放状态,因此,在加载 View 时,仅当尚未播放音乐时才播放音乐。

 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"music"] == nil) {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"drums" ofType:@"mp3"];
    theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPathath] error:NULL];
    theAudio.delegate = self;
    theAudio.numberOfLoops = -1;
    [theAudio play]; 
    [[NSUserDefaults standardUserDefaults] setObject:@"-" forKey:@"music"]; }

退出应用程序时,您需要将此键重置为nil。否则,如果播放器退出了该应用程序,并且下次重新启动该应用程序时,@“music”字符串将不会为零。

转到 projectAppDelegate.m 文件:
- (void)applicationDidEnterBackground:(UIApplication *)application {
        [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"music"]; }

如果要在整个应用程序中播放音乐,请按照以下所示放置音乐播放代码,以确保安全。不要忘记在projectAppDelegate.h文件中声明AVAudioPlayer * theAudio。
- (void)applicationDidBecomeActive:(UIApplication *)application {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"drums" ofType:@"mp3"];
    theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPathath] error:NULL];
    theAudio.delegate = self;
    theAudio.numberOfLoops = -1;
    [theAudio play]; 
    [[NSUserDefaults standardUserDefaults] setObject:@"-" forKey:@"music"]; }

我可能在这里错过了一些。只需运行一些测试,使其成为您喜欢的工作方式即可。我只是尝试了我的应用程序,它为我工作。

关于ios - iOS背景音乐问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9902738/

相关文章:

Android - 使用彩信发送音频文件

audio - 使用 gstreamer 将同步的视频和音频记录到容器文件中

javascript - Cordova - 操作系统升级后应用程序在 iOS/Android 上崩溃

ios - 以编程方式访问 Apple Notes 内容

objective-c - 由于缺少入口点,场景无法访问...自定义按钮

audio - 视频中用于音频流的H264

ios - Travis-ci 卡在 pod 安装中

ios - 如何将 UIImageView 放置在导航栏上

swift - 不同项目中的SPM依赖

ios - 带有 SDK 绝对路径的 xcodebuild 命令