菜鸟教程小白 发表于 2022-12-11 17:12:47

ios - 音频播放未在 Swift 中恢复到原始音量


                                            <p><p>我正在尝试播放“叮”声以提醒用户注意事件。播放“叮”声,但背景音频(在本例中为默认的 Music.App)在播放 clang 后未恢复到其原始音量。但是,关闭应用程序后它将恢复正常音量。这就是我所拥有的:</p>

<p>这是我设置 Audio Session 类别的地方:</p>

<pre><code>   public override func viewDidLoad() {
            super.viewDidLoad()
            do {
                try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.DuckOthers)
                //refer to this link for swift&#39;s sound reference: https://developer.apple.com/ios/human-interface-guidelines/interaction/audio/
            } catch {
                print(&#34;unable to load audio session&#34;)
            }
            ....
   }
</code></pre>

<p>这是我调用函数的地方:</p>

<pre><code>if(!currentTimer.launchedNotification){
            playFinishedSound()
            AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) //handles phone vibration
            audioPlayerDidFinishPlaying(audioPlayer!, successfully: true)

      }
</code></pre>

<p>这是我的私有(private)功能:</p>

<pre><code>private func playFinishedSound(){
      if let pathResource = NSBundle.mainBundle().pathForResource(&#34;Ding&#34;, ofType: &#34;wav&#34;){
            let soundToPlay = NSURL(fileURLWithPath: pathResource)
            do {
                audioPlayer = try AVAudioPlayer(contentsOfURL: soundToPlay)
                if(audioPlayer!.prepareToPlay()){
                  print(&#34;preparation success&#34;)
                  audioPlayer!.delegate = self
                  setAVAudioSession()
                  if(audioPlayer!.play()){
                        print(&#34;Sound play success&#34;)
                  }else{
                        print(&#34;Sound file could not be played&#34;)
                  }
                }else{
                  print(&#34;preparation failure&#34;)
                }

            }catch{
                print(&#34;Sound file could not be found&#34;)
            }
      }else{
            print(&#34;path not found&#34;)
      }
    }
</code></pre>

<p>这是我设置 Audio Session 的地方:</p>

<pre><code>private func setAVAudioSession() {
      let session:AVAudioSession = AVAudioSession.sharedInstance()
      do{
            try session.setActive(true)
            print(&#34;session is active&#34;)
      }catch{
            print(&#34;could not make session active&#34;)
      }
    }
</code></pre>

<p>这是 AVAudioPlayerDelegate 协议(protocol)的委托(delegate)方法:</p>

<pre><code>public func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
      do {
            player.stop()
            try AVAudioSession.sharedInstance().setActive(false, withOptions: AVAudioSessionSetActiveOptions.NotifyOthersOnDeactivation)
            player.prepareToPlay()
            print(&#34;Session stopped successfully&#34;)
      }catch{
            print(&#34;Could not end audio session&#34;)
      }
    }
</code></pre>

<p>同样,问题是如果在后台播放音乐,音乐音量会变小,但是当 Audio Session 处于非事件状态时,音乐音量不会恢复正常。 </p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>在对此进行试验后,我的解决方案效果很好。唯一需要注意的是,如果您尝试快速连续播放倒计时声音或其他声音,则设备播放声音会出现延迟,因此可能需要一些线程管理或其他方法来解决该问题。欢迎对此解决方案进行任何改进。 </p>

<pre><code>private let session = AVAudioSession.sharedInstance()

private func setSession(isActive: Bool) {
    if isActive {
      try! session.setCategory(AVAudioSession.Category.playback, options: AVAudioSession.CategoryOptions.duckOthers)
    } else {
      try! session.setCategory(AVAudioSession.Category.ambient, options: AVAudioSession.CategoryOptions.mixWithOthers)
    }
    try! self.session.setActive(isActive, options: .notifyOthersOnDeactivation)
}
</code></pre>

<p>当您要播放、暂停或停止音频时,请调用此方法。 </p>

<ol>
<li><p>将类别设置为 <code>playback</code> 并将选项设置为 <code>duckOthers</code> 可确保您的播放音量最大,而其他音频的音量会降低。</p></li >
<li><p>将类别设置为 <code>ambient</code> 并将选项设置为 <code>mixWithOthers</code> 可确保您的播放与其他音频类型相同,从而导致音频恢复到原来的音量在播放之前。</p></li>
<li><p>最后将音频状态设置为事件或非事件(<code>setActive</code>)</p></li>
</ol>

<p><strong>注意事项:</strong></p>

<p>使用 <code>try!</code> 肯定不是推荐的做法,我提供此代码是为了让您顺利进行。在适用的情况下实现最佳安全实践。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 音频播放未在 Swift 中恢复到原始音量,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/38836412/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/38836412/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 音频播放未在 Swift 中恢复到原始音量