问题
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