3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

swift5でミュート中でも音を出す方法

Posted at

初めに

今回はミュート中でも音を出す方法を展開します。タイトル通りですね。。。
## 実装
今回はViewを立ち上げたら音が鳴り始めることにします。
コメントに詳細書きます。

TestViewController.swift
import UIKit
import AVFoundation

class TestViewController: UIViewController {
    var audioPlayer: AVAudioPlayer!
    override func viewDidLoad() {
        super.viewDidLoad()

        // mp3音声の再生 testSoundの音声ファイルがあると仮定します。
        playSound(name: "testSound")
    }
}
extension TestViewController: AVAudioPlayerDelegate {
    func playSound(name: String) {
        guard let path = Bundle.main.path(forResource: name, ofType: "mp3") else { return }
        
        do {
            //ここでミュート中でも音が出るようになります。
            try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
            do {
                //オーディオセッションをアクティブにする(ここも必要)
                try AVAudioSession.sharedInstance().setActive(true)
                // AVAudioPlayerのインスタンス化
                audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
                // AVAudioPlayerのデリゲートをセット
                audioPlayer.delegate = self
                // 音声の再生
                audioPlayer.play()
                
            } catch _ as NSError {
            }
        } catch _ as NSError {
        }
    }
}

終わりに

短文でミュートの設定でも音が出るようになります。
悪用厳禁です。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?