avplayer has no sounds when play video

☆樱花仙子☆ 提交于 2019-12-12 09:28:53

问题


here is all my codes for play a mp4,the mp4 is playing but no sounds out

import UIKit

import AVFoundation
class ViewController: UIViewController {

@IBOutlet weak var containerView: UIView!

var playerLayer:AVPlayerLayer!
var player:AVPlayer!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let path = NSBundle.mainBundle().pathForResource("huoguo", ofType: "mp4")
    let url = NSURL(fileURLWithPath: path!)
    let asset = AVAsset(URL: url)
    let playerItem = AVPlayerItem(asset: asset)
    self.player = AVPlayer(playerItem: playerItem)
    self.playerLayer = AVPlayerLayer(player: player)
    self.playerLayer.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.width * 9 / 16)
    self.containerView.layer.addSublayer(playerLayer)
    //self.playerLayer.player?.volume = 1
    self.playerLayer.player?.play()
}
}

i'm sure it has sounds,because i can hear when play the mp4 using VLC, did i miss something ?


回答1:


Check your phone is silent mode or not. If it is silent try add code below to viewDidLoad:

Swift 2.3

try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: [])

Swift 3

try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: [])



回答2:


For Swift 4.2, put following lines in viewDidLoad

do {
    try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])
}
catch {
    print("Setting category to AVAudioSessionCategoryPlayback failed.")
}



回答3:


Check if the iPhone has silent mode engaged, it is a button above the 2 top left buttons. A toggle switch that allows silent mode.




回答4:


I had multiple view controllers that needed to play audio even when the device what set to mute. So instead of updating every single viewDidLoad, I added the following to the didFinishLaunchingWithOptions method in the AppDelegate.swift file.

try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)

Notes:

  • import AVFoundation
  • I didn't need any other error catching so I just used try?.
  • I am supporting down to iOS 9. Gang Fang's answer required iOS 10. Only using the single parameter as I did above, though, worked fine for iOS 9.
  • Tested with Swift 5


来源:https://stackoverflow.com/questions/34735268/avplayer-has-no-sounds-when-play-video

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!