在应用中播放背景音乐?

时间:2015-07-15 05:17:21

标签: ios swift audio avfoundation avaudioplayer

我希望用户能够打开应用并开始播放音乐。我希望用户能够在没有音乐停止的情况下转到任何视图控制器并返回到初始控制器。我希望它无限循环。

我试图将初始视图控制器的viewDidLoad方法放入其中以开始播放。发生的情况是,用户离开初始视图控制器,当他们回来时,音乐再次开始播放,与原始副本重叠。

为了解决这个问题,我设置了一个if语句,检查声音是否已经播放以不启动另一个副本,并且viewDidLoad方法完全忽略if语句并且无论如何再次播放它。我也尝试过使用viewDid/WillAppear。我尝试用applicationDidLaunchWithOptions方法将声音放在app委托中,我完全沉默了。

8 个答案:

答案 0 :(得分:9)

使用单身人士也可以:

int systick_timer_counter = 0;

void reset_systick()
{
    systick_timer_counter = 0;
}

void SysTick_Handler()
{
    systick_timer_counter++;
}

int return_systick()
{
    return systick_timer_counter;
}

然后你可以在任何类中使用它(根据Swift 2.1)

import AVFoundation

class MusicHelper {
    static let sharedHelper = MusicHelper()
    var audioPlayer: AVAudioPlayer?

    func playBackgroundMusic() {
        let aSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("coolsong", ofType: "mp3")!)
        do {
            audioPlayer = try AVAudioPlayer(contentsOfURL:aSound)
            audioPlayer!.numberOfLoops = -1
            audioPlayer!.prepareToPlay()
            audioPlayer!.play()
        } catch {
            print("Cannot play the file")
        }
    }
}

答案 1 :(得分:3)

这就是我的做法。将此代码添加到您希望音乐开始播放的课程场所外的任何位置。你甚至可以创建一个全新的Swift文件,只需在其中添加此代码(导入AVFoundation)

SELECT   group_id 
         ,Sum(value) AS sum_value
         ,Sum((name LIKE '%me%')::int) AS count_value 
FROM     table
GROUP BY group_id;

完成后,转到didMoveToView函数并使用文件名调用该函数。

var backgroundMusicPlayer: AVAudioPlayer!

func playBackgroundMusic(filename: String) {

    //The location of the file and its type
    let url = NSBundle.mainBundle().URLForResource(filename, withExtension: "mp3")

    //Returns an error if it can't find the file name
    if (url == nil) {
        println("Could not find the file \(filename)")
    }

    var error: NSError? = nil

    //Assigns the actual music to the music player
    backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)

    //Error if it failed to create the music player
    if backgroundMusicPlayer == nil {
    println("Could not create audio player: \(error!)")
    return
    }

    //A negative means it loops forever
    backgroundMusicPlayer.numberOfLoops = -1
    backgroundMusicPlayer.prepareToPlay()
    backgroundMusicPlayer.play()
}

我刚试过它,切换场景后效果很好。

答案 2 :(得分:2)

只需添加" numberofLoops = -1"它在后台无限播放。

示例(Swift):

func playBackgroundMusic() {
    do {
        if let bundle = NSBundle.mainBundle().pathForResource("someMP3file", ofType: "mp3") {
            let alertSound = NSURL(fileURLWithPath: bundle)
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            try AVAudioSession.sharedInstance().setActive(true)
            try audioPlayer = AVAudioPlayer(contentsOfURL: alertSound)
            audioPlayer.numberOfLoops = -1
            audioPlayer.prepareToPlay()
            audioPlayer.play()

        }
    } catch {
        print(error)
    }
}

玩得开心。

答案 3 :(得分:1)

找到解决方案。我声明了一个名为signal的视图控制器属性。我说信号:布尔? - 然后在viewDidLoad中,如果signal == nil,我将if语句只播放背景歌曲。然后,在我的其他视图控制器中,我将其设置为当它们回到主视图控制器时,信号属性= false。然后,这首歌不再播放,一切正常。

答案 4 :(得分:0)

对于swift 4:

func playBackgroundMusic() {
        let aSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "music", ofType: "mp3")!)
        do {
            audioPlayer = try AVAudioPlayer(contentsOf:aSound as URL)
            audioPlayer!.numberOfLoops = -1
            audioPlayer!.prepareToPlay()
            audioPlayer!.play()
        } catch {
            print("Cannot play the file")
        }
    }

答案 5 :(得分:0)

Swift 4.2更新 **新建一个班级,然后粘贴以下代码:........... **

SingleTransformer

.............将此代码添加到视图控制器.......

<!DOCTYPE html>
<?php 
session_start();
print "
<html>
</head>
<body>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#body {
  display:none;
  width: 100%;
  padding: 5px 0;
  text-align: left;
  background-color: lightblue;
  margin-top: 5px;}
</style>
</head>
<body>
<font size=+5><b>Why would we make a refund and what is the process?</b></font><br>
<div id="body1"><br><br>
  <div>
  <a href='#' class='articleTitle'><font size="+1"><b>The first thing is the circumstances Under which we would make a refund. There are 2 reasons:</b></font></a>
  <div class='showArticle'>
    <p>1. The first reason for a refund would be an Ebay job that we are unable to complete for whatever reason.<br>
     2. The other reason for a refund would be as resolution of a warranty.
  </div>
  </div>
<div id="body2">
  <div>
  <a href='#' class='articleTitle'><font size="+1"><b>How do we process a refund?</b></font></a>
  <div class='showArticle'>
    <p>1. To process a refund for an Ebay job, follow <a href="https://docs.google.com/a/helpscore.com/viewer?a=v&pid=sites&srcid=aGVscHNjb3JlLmNvbXxraG9hdGVzdHxneDo1NTgyZTA4OTk0YzM3MzU0"><b>instructions</b></a> to be sure all steps are being followed correctly, then send an email to have the refund processed.<br>
    2. In the case of a refund as part of the <a href="https://docs.google.com/a/helpscore.com/viewer?a=v&pid=sites&srcid=aGVscHNjb3JlLmNvbXxraG9hdGVzdHxneDozOWEyZWMwZjBjYzVlYzg5"><b>Warranty Process</b></a>, you must have the customer's agreement and forward that to the refund email address.<br><br>
  </div>
  </div>
<div id="body3">
  <div>
  <a href='#' class='articleTitle'><font size="+1"><b>What is the refund email address and email content?</b></font></a>
  <div class='showArticle'>
    <p>When requesting a refund, please forward the customer's refund acceptance and change the subject to: <b>"Please refund customer $"</b><br>
  Please be sure to use the correct <a href="https://docs.google.com/a/helpscore.com/viewer?a=v&pid=sites&srcid=aGVscHNjb3JlLmNvbXxraG9hdGVzdHxneDo1ZThiZjdkNWZiZGIwOWZl"><b>Template</b></a>. You will have to download the file to access it correctly.<br>
  Here is the note to leave after you have sent the refund request: Refund Request sent<br>
  The email address to send the request to is: PSrefunds@porch.com
  </div>
  </div>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js' type='text/javascript'></script>
<script type='text/javascript'>
$(document).ready(function(){

$('.showArticle').hide();
$('.articleTitle').show();

$('.showComments').hide();
$('.commentTitle').show();

$('.articleTitle').click(function(){
$(this).next('.showArticle').slideToggle();
});

$('.commentTitle').click(function(){
$(this).next('.showComments').slideToggle();

});
});
</script>
</body>
</html>

答案 6 :(得分:0)

解决了ALHAMDULELLAH仅在Xcode设置中更改的问题

  
    

转到设置页面>>功能>>背景>>模式>>允许音频文件     enter image description here

  

答案 7 :(得分:-2)

我认为你应该尝试使用AppDelegate.swift文件。 在方法应用程序(..... didFinishLaunchingWithOptions .....){}中定义你的AVAudioPlayer()和.play()