在 iOS 应用中播放 mp3 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16879368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:46:32  来源:igfitidea点击:

playing a mp3 file in iOS app

iosavaudioplayer

提问by user2444410

I can't figure out how to play a music file in an iPhone game.

我不知道如何在 iPhone 游戏中播放音乐文件。

Im creating a Game and I am trying to figure out how to play music whenever the app is launched.

我正在创建一个游戏,我试图弄清楚在启动应用程序时如何播放音乐。

I tried this:

我试过这个:

- (void)awakeFromNib {

    NSString *path = [[NSBundle mainBundle] pathForResource:@"musicamenu" ofType:@"mp3"];

    AVAudioPlayer *theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];

    [theAudio play];


}

回答by Sam B

This is how you do it. In your v1AppDelegate.h file add

这就是你如何做到的。在您的 v1AppDelegate.h 文件中添加

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

@interface v1AppDelegate : UIResponder <UIApplicationDelegate>
{
    AVAudioPlayer *myAudioPlayer;
}

@property (nonatomic, retain) AVAudioPlayer *myAudioPlayer;

@property (strong, nonatomic) UIWindow *window;

@end

Now in your v1AppDelegate.m file add this

现在在你的 v1AppDelegate.m 文件中添加这个

#import "v1AppDelegate.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

@implementation v1AppDelegate

@synthesize window = _window;

@synthesize myAudioPlayer;


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    //start a background sound
    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"Soothing_Music2_Long" ofType: @"mp3"];
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath ];    
    myAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
    myAudioPlayer.numberOfLoops = -1; //infinite loop
    [myAudioPlayer play];


    // Override point for customization after application launch.
    return YES;
}

If you wish to stop or start this music from anywhere else in your code then simply add this

如果您想从代码中的任何其他地方停止或开始播放此音乐,只需添加此

#import "v1AppDelegate.h"    
- (IBAction)stopMusic
    {
        v1AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
        [appDelegate.myAudioPlayer stop];
    }


    - (IBAction)startMusic
    {
        v1AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
        [appDelegate.myAudioPlayer play];
    }

回答by sunkehappy

I recommend to add the play music method in applicationDidBecomeActive:method. Because you want the music played every time the app is launched. Note you should hold a reference to the player. Else the music will not be played.

我建议在applicationDidBecomeActive:方法中添加播放音乐方法。因为您希望每次启动应用程序时都播放音乐。请注意,您应该持有对播放器的引用。否则音乐将不会播放。

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Play music on another queue so that the main queue is not blocked.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self playMusic];
    });
}

- (void)playMusic
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"done" ofType:@"mp3"];
    NSError *error = nil;
    NSURL *url = [NSURL fileURLWithPath:path];
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    [self.player play];
}

回答by Kevin ABRIOUX

For Swift 3.1 :

对于 Swift 3.1 :

Use this two imports :

使用这两个导入:

import AVFoundation
import AudioToolbox

Create a reference for your AVAudioPlayer :

为您的 AVAudioPlayer 创建一个参考:

private var mAudioPlayer : AVAudioPlayer?

Use this function for play a sound you are storing in your app :

使用此功能播放您存储在应用程序中的声音:

func onTapSound(){
        let soundFile = Bundle.main.path(forResource: "slap_placeholder.wav", ofType: nil)
        let url = URL(fileURLWithPath: soundFile!)
        self.mAudioPlayer = try! AVAudioPlayer(contentsOf: url as URL)
        self.mAudioPlayer?.play()
}