ios 使用 iPhone SDK 播放 MP3 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1973902/
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 16:44:08  来源:igfitidea点击:

Play MP3 Files with iPhone SDK

iosaudio

提问by Momi

What's the easiest way to play a music file such as Mp3 with pause button? very very simple a button play and another button pause that music

使用暂停按钮播放音乐文件(例如 Mp3)的最简单方法是什么?非常非常简单的一个按钮播放和另一个按钮暂停音乐

回答by Nithin

These are the codes for the requested actions, appSoundPlayer is a property of AVAudioPlayer declared in h file. Also this example plays a song in the resource folder.

这些是请求操作的代码,appSoundPlayer 是在 h 文件中声明的 AVAudioPlayer 的一个属性。此示例还播放资源文件夹中的歌曲。

#pragma mark -
    #pragma mark *play*
    - (IBAction) playaction {

        NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"songname" ofType:@"mp3"];
        NSURL *newURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
        self.soundFileURL = newURL;
        [newURL release];
        [[AVAudioSession sharedInstance] setDelegate: self];
        [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil];

    // Registers the audio route change listener callback function
    AudioSessionAddPropertyListener (
                                     kAudioSessionProperty_AudioRouteChange,
                                     audioRouteChangeListenerCallback,
                                     self
                                     );

    // Activates the audio session.

    NSError *activationError = nil;
    [[AVAudioSession sharedInstance] setActive: YES error: &activationError];

    AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: soundFileURL error: nil];
    self.appSoundPlayer = newPlayer;
    [newPlayer release];
    [appSoundPlayer prepareToPlay];
    [appSoundPlayer setVolume: 1.0];
    [appSoundPlayer setDelegate: self];
    [appSoundPlayer play];


    [stopbutton setEnabled:YES];
    [playbutton setEnabled: NO];
    playbutton.hidden=YES;
    pausebutton.hidden =NO;
}//playbutton touch up inside

#pragma mark -
#pragma mark *pause*
-(IBAction)pauseaction {
    [appSoundPlayer pause];
    pausebutton.hidden = YES;
    resumebutton.hidden = NO;

}//pausebutton touch up inside

#pragma mark -
#pragma mark *resume*
-(IBAction)resumeaction{
    [appSoundPlayer prepareToPlay];
    [appSoundPlayer setVolume:1.0];
    [appSoundPlayer setDelegate: self];
    [appSoundPlayer play];
    playbutton.hidden=YES;
    resumebutton.hidden =YES;
    pausebutton.hidden = NO;

}//resumebutton touch up inside

#pragma mark -
#pragma mark *stop*
-(IBAction)stopaction{

    [appSoundPlayer stop];
    [playbutton setEnabled:YES];
    [stopbutton setEnabled:NO];
    playbutton.hidden=NO;
    resumebutton.hidden =YES;
    pausebutton.hidden = YES;

}//stopbutton touch up inside

回答by Julio Bailon

For short sounds or when the MP3 does not play well on the suggested code you can always use:

对于短声音或当 MP3 在建议的代码上播放效果不佳时,您可以始终使用:

SystemSoundID soundID; 
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/sound.mp3", [[NSBundle mainBundle] resourcePath]]];

AudioServicesCreateSystemSoundID((CFURLRef)url, &soundID); 
AudioServicesPlaySystemSound (soundID);

Don't forget to add:

不要忘记添加:

#import <AudioToolbox/AudioToolbox.h>

回答by Madhup Singh Yadav

well hereis a good tutorial available.

那么这里有一个很好的教程。

The theme is

主题是

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/audiofile.mp3", [[NSBundle mainBundle] resourcePath]]];

    NSError *error;
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    audioPlayer.numberOfLoops = -1;

[audioPlayer play];

and when you want to pause;

当你想暂停时;

[audioPlayer pause];

hope this helps.

希望这可以帮助。

回答by Hashim Akhtar

I'm afraid the answer stated no longer works in iOS 7 and above. You will need to use the following code:

恐怕上述答案不再适用于 iOS 7 及更高版本。您将需要使用以下代码:

in the header file (.h)

在头文件 (.h) 中

In order to handle the delegate methods like when the playing of the audio has finished audioPlayerDidFinishPlaying:, inherit from AVAudioPlayerDelegate .

为了处理音频播放完成时的委托方法 audioPlayerDidFinishPlaying: ,继承自 AVAudioPlayerDelegate 。

@property (nonatomic, strong) AVAudioPlayer *player;

in the implementation file (.m)

在实现文件 (.m) 中

 NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: resourceName
                                                          ofType: @"mp3"];
 NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];

 AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
                                                                  error: nil];
_player = newPlayer;
[_player prepareToPlay];
[_player setDelegate: self];
[_player play];

回答by Nhat Dinh

I like simple code and here is my solution : (Remember to add switch button to get music play. Have fun)

我喜欢简单的代码,这是我的解决方案:(记得添加开关按钮来播放音乐。玩得开心)

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface ViewController ()
{
    NSURL*                  bgURL;
    AVAudioPlayer*          bgPlayer;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    bgURL = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"mp3"]];
    bgPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:bgURL error:nil];
}

#pragma mark AVAudioPlayer
- (IBAction)toggleMusic:(UISwitch*)sender {
    NSLog(@"togging music %s", sender.on ? "on" : "off");

    if (bgPlayer) {

        if (sender.on) {
            [bgPlayer play];
        }
        else {
            [bgPlayer stop];
        }
    }   
}

回答by bw1024

The oalTouchsample code on the Apple iOS developer web site does what you want, and is ready to run.

oalTouch对苹果iOS开发者的网站示例代码你想要做什么,并准备运行。

It also shows how to test if another app (eg ipod) is playing a file already, which is handy if you want to allow your users to listen to their own music instead of yours.

它还展示了如何测试另一个应用程序(例如 ipod)是否已经在播放文件,如果您想让您的用户听他们自己的音乐而不是您的音乐,这会很方便。

回答by Jim Huang

DIRAC API is free and quite easy to use. We've used it in my talking robot app http://itunes.apple.com/us/app/daidai/id484833168and it has been amazing to me how it manages to change the speed and pitch of voice

DIRAC API 是免费的并且非常易于使用。我们已经在我的会说话的机器人应用程序http://itunes.apple.com/us/app/daidai/id484833168 中使用了它,我很惊讶它如何设法改变声音的速度和音调

http://www.dspdimension.com/download/

http://www.dspdimension.com/download/

回答by Mongus Pong

The Apple documentation hereshould have everything you need to know.

此处的 Apple 文档应该包含您需要了解的所有信息。