【问题标题】:Playing music within app在应用内播放音乐
【发布时间】:2025-12-16 02:35:01
【问题描述】:

即使用户更改视图控制器等,我也想在整个应用程序中播放配乐。我有一个来自配乐的循环,我想在它完成后重复。我目前正在通过以下方式播放声音:

NSString *soundFile = [[NSBundle mainBundle]
                       pathForResource:@"Click03" ofType:@"wav"];
AVAudioPlayer  *audioPlayer = [[AVAudioPlayer alloc]
               initWithContentsOfURL:[NSURL fileURLWithPath: soundFile]
               error:nil];
[audioPlayer start];
 // or [audioPlayer stop];

我不太确定这是否是播放声音的最佳方式。有人可以向我解释如何做我上面问的吗?提前致谢!

【问题讨论】:

    标签: objective-c ios core-audio


    【解决方案1】:

    基本上你正在尝试播放背景音频..

    查看以下链接对您有帮助

    Play music in the background using AVAudioplayer

    http://www.sagorin.org/2011/11/29/ios-playing-audio-in-background-audio/

    要重复音频,请查看此链接

    How do I repeat a AVAudioPlayer?

    【讨论】:

      【解决方案2】:

      编写代码以在 Appdelegate 中播放声音。

      -(void)PlaySound:(NSString*)strSoundFileName 
      {
          fileURL=[[NSURL alloc] initFileURLWithPath:strSoundFileName];
          audioPlayer=[[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
          audioPlayer.delegate=self;
          [audioPlayer prepareToPlay];
      
          audioPlayer.currentTime=0;
          [audioPlayer play];
          audioPlayer.numberOfLoops=-1;
      }
      

      【讨论】: